packagecom.dgjianke.ch03;/*** 关于二进制数据的一些操作
*@authordgjianke
**/
public classBitManipulation {/*** 打印出整型数据在机器中的二进制形式
*@parami 整型数据*/
public static void printIntBinary(inti) {for(int j=31;j>=0;j--) {if(((1 << j) & i)==0) {
System.out.print(0);
}else{
System.out.print(1);
}
}
System.out.println();
}/*** 打印出长整型数据在机器中的二进制形式
*@parami 长整形数据*/
public static void printLongBinary(longi) {for(int j=63;j>=0;j--) {if(((1L << j) & i)==0) { //注意这里为1L,否则不会按64位处理
System.out.print(0);
}else{
System.out.print(1);
}
}
System.out.println();
}public static void printShortBinary(shorti) {for(int j=15;j>=0;j--) {if(((1 << j) & i)==0) {
System.out.print(0);
}else{
System.out.print(1);
}
}
System.out.println();
}public static voidmain(String args[]) {int i = 1;int j = -1;//printIntBinary(i);//结果为:00000000000000000000000000000001//printIntBinary(j);//结果为:11111111111111111111111111111111
long k = 3;long l = -3;
printLongBinary(j);//long转int也是把低32位赋值给int类型//printLongBinary(k);//结果为:0000000000000000000000000000000000000000000000000000000000000001//printLongBinary(l);//结果为:1111111111111111111111111111111111111111111111111111111111111111
short s = -1;
printShortBinary(s);//运算顺序:1. s转成int类型所以二进制为:11111111111111111111111111111111//2. 再对这个int类型s进行移位运算结果:00000000001111111111111111111111
printIntBinary(s>>>10);//运算顺序:1. s转成int类型所以二进制为:11111111111111111111111111111111//2. 再对这个int类型s进行移位运算结果:00000000001111111111111111111111//3. 再将值赋值给s这个short类型,取低十六位进行赋值,结果为:1111111111111111(8个1),即十进制的-1//4. 将值传给printIntBinary时,s再转成int类型,所以二进制为:11111111111111111111111111111111
printIntBinary(s>>>=10);//printIntBinary(~s);
byte b = -1;//printIntBinary(b);
System.out.println(b>>>10); //结果为:4194303
System.out.println(b>>>=10);//结果为:-1(原理和上面相同,只不过由低十六位换成了低八位)
System.out.println(b>>>28);//结果为:15,这里实际打印int类型
System.out.println(b>>>=28);//结果为:15,这里实际打印byte类型,总之高位转低位是按低位来赋值 的
}
}