Java算法:二进制和位运算
来源:左程云算法
public class Main {
public static void main(String[] args) {
int a=78;
System.out.println(a);
printBinary(a);
System.out.println("----a-----");
//负数
int b=-6;
System.out.println(b);
printBinary(b);
System.out.println("----b-----");
//二进制形式定义变量
int c=0b1001110;
System.out.println(c);
printBinary(c);
System.out.println("----c-----");
//十六进制形式定义变量
int d=0x4e;
System.out.println(d);
printBinary(d);
System.out.println("----d-----");
//~ 相反数
System.out.println(a);
printBinary(a);
printBinary(~a);
int e=~a+1;
System.out.println(e);
printBinary(e);
System.out.println("---e----");
//int long的最小值,取相反数绝对值都是自己
int f=Integer.MIN_VALUE;
System.out.println(f);
printBinary(f);
System.out.println(-f);
printBinary(-f);
System.out.println(~f+1);
printBinary(~f+1);
System.out.println("----f----");
//| & ^
int g=0b0001010;
int h=0b0001100;
printBinary(g|h);
printBinary(g&h);
printBinary(g^h);
System.out.println("----g,h----");
//
System.out.println("test1测试开始");
boolean test1=returntrue()|returnfalse();
System.out.println("test1结果:"+test1);
System.out.println("test2测试开始");
boolean test2=returntrue()||returnfalse();
System.out.println("test2结果:"+test2);
System.out.println("test3测试开始");
boolean test3=returnfalse()&returntrue();
System.out.println("test3结果:"+test3);
System.out.println("test4测试开始");
boolean test4=returnfalse()&&returntrue();
System.out.println("test4结果:"+test4);
System.out.println("----|,||,&,&&-----");
//<<
int i=0b0011010;
printBinary(i);
printBinary(i<<1);
printBinary(i<<2);
printBinary(i<<3);
System.out.println("---i<<----");
// 非负数 >> >>>效果一样
printBinary(i);
printBinary(i>>2);
printBinary(i>>>2);
//负数 >> >>>效果不一样
int j=0b11110000000000000000000000000000;
printBinary(j);
printBinary(j>>2);
printBinary(j>>>2);
System.out.println("----j>> >>>----");
//
int k=10;
System.out.println(k);
System.out.println(k << 1);
System.out.println(k << 2);
System.out.println(k << 3);
System.out.println(k >> 1);
System.out.println(k >> 2);
System.out.println(k >> 3);
System.out.println("===k===");
}
public static boolean returntrue()
{
System.out.println("进入了returnTrue函数");
return true;
}
public static boolean returnfalse()
{
System.out.println("进入了returnfalse函数");
return false;
}
public static void printBinary(int num)
{
//打印int类型的数字,32位状态
for(int i=31;i>=0;i--)
{
System.out.print((num&(1<<i))==0?"0":'1');
}
System.out.println();
}
}