Java位运算
1、按位取反 ~
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(1));
System.out.println(Integer.toBinaryString(~1));
System.out.println(Integer.toBinaryString(5));
System.out.println(Integer.toBinaryString(~5));
}
}
2、按位与 &
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(6));
System.out.println(Integer.toBinaryString(3));
System.out.println(Integer.toBinaryString(6&3));
}
}
3、按位或 |
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(6));
System.out.println(Integer.toBinaryString(2));
System.out.println(Integer.toBinaryString(6|2));
}
}
4、按位异或 ^
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(6));
System.out.println(Integer.toBinaryString(2));
System.out.println(Integer.toBinaryString(6^2));
}
}
5、按位左位移 <<
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(1));
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE-1)));
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE)));
System.out.println(Integer.toBinaryString(1<<(Integer.SIZE+1)));
System.out.println(1<<(Integer.SIZE+1));
System.out.println(Integer.toBinaryString(-1));
System.out.println(Integer.toBinaryString(-1<<3));
System.out.println(Integer.toBinaryString(-1<<(Integer.SIZE-1)));
}
}
6、按位右位移 >>
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(-30));
System.out.println(Integer.toBinaryString(-30>>1));
System.out.println(Integer.toBinaryString(16));
System.out.println(Integer.toBinaryString(16>>3));
}
}
7、无符号右位移 >>>
public class TestBitOperation {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(-30));
System.out.println(Integer.toBinaryString(-30>>>1));
System.out.println(Integer.toBinaryString(16));
System.out.println(Integer.toBinaryString(16>>>3));
}
}