Java位运算
1、按位取反 ~
public class TestBitOperation {
public static void main(String[] args) {
//~n: 按位取反,0 -> 1, 1 -> 0
System.out.println(Integer.toBinaryString(1));
//1
System.out.println(Integer.toBinaryString(~1));
//11111111111111111111111111111110
System.out.println(Integer.toBinaryString(5));
//101
System.out.println(Integer.toBinaryString(~5));
//11111111111111111111111111111010
}
}
2、按位与 &
public class TestBitOperation {
public static void main(String[] args) {
//& 按位与 可以把1看做true,把0看成false,只有都为true的时候,结果才为true
//也就是说 二进制情况下,只有在该位上都为1的时候结果才为1,否则为0
System.out.println(Integer.toBinaryString(6));//110
System.out.println(Integer.toBinaryString(3));//11
System.out.println(Integer.toBinaryString(6&3));//10
}
}
3、按位或 |
public class TestBitOperation {
public static void main(String[] args) {
// | 按位或,在该位上只要有一个1,结果就为1,否则为0
System.out.println(Integer.toBinaryString(6));//110
System.out.println(Integer.toBinaryString(2));//10
System.out.println(Integer.toBinaryString(6|2));//110
}
}
4、按位异或 ^
public class TestBitOperation {
public static void main(String[] args) {
// ^ 按位异或,在该位上的值相同时,结果为0,不同时为1
System.out.println(Integer.toBinaryString(6));//110
System.out.println(Integer.toBinaryString(2));//10
System.out.println(Integer.toBinaryString(6^2));//100
}
}
5、按位左位移 <<
public class TestBitOperation {
public static void main(String[] args) {
// << 按位左位移,不管该数是正数还是负数,右边都补0。
// 如果超出了该数据类型的位数,则从头开始
System.out.println(Integer.toBinaryString(1));//1
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE-1)));
//10000000000000000000000000000000
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE)));//1
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE+1)));//10
System.out.println(1<<(Integer.SIZE+1));//2
System.out.println(Integer.toBinaryString(-1)); //11111111111111111111111111111111
System.out.println(Integer.toBinaryString(-1<<3));
//11111111111111111111111111111000
System.out.println(Integer.toBinaryString(-1<<(Integer.SIZE-1)));
//10000000000000000000000000000000
}
}
6、按位右位移 >>
public class TestBitOperation {
public static void main(String[] args) {
// >> 按位右位移,是正数,左边补0;是负数,左边补1
System.out.println(Integer.toBinaryString(-30));
//11111111111111111111111111100010
System.out.println(Integer.toBinaryString(-30>>1));
//11111111111111111111111111110001
System.out.println(Integer.toBinaryString(16));//10000
System.out.println(Integer.toBinaryString(16>>3));//10
}
}
7、无符号右位移 >>>
public class TestBitOperation {
public static void main(String[] args) {
// >> 按位右位移,是正数,左边补0;是负数,左边补1
System.out.println(Integer.toBinaryString(-30));
//11111111111111111111111111111111
System.out.println(Integer.toBinaryString(-30>>>1));//左边补0
//1111111111111111111111111110001
System.out.println(Integer.toBinaryString(16));//10000
System.out.println(Integer.toBinaryString(16>>>3));//10
}
}