// 位与 &(1&1=1 1&0=0 0&0=0)
System.out.println("the 4 is " + Integer.toBinaryString(4));
System.out.println("the 6 is " + Integer.toBinaryString(6));
System.out.println("the 4 & 6 is " + Integer.toBinaryString(4 & 6));
------------------------------------------------------------------------------------------------
结果:the 4 is 100
the 6 is 110
the 4 & 6 is 100
3、位或
// 位或 &(1|1=1 1|0=0 0|0=0)
System.out.println("the 4 is " + Integer.toBinaryString(4));
System.out.println("the 6 is " + Integer.toBinaryString(6));
System.out.println("the 4 | 6 is " + Integer.toBinaryString(4 |6));
------------------------------------------------------------------------------------------------
结果:the 4 is 100
the 6 is 110
the 4 | 6 is 110
4、位非
// 位非 |(~1=0 ~0=1)
System.out.println("the 4 is " + Integer.toBinaryString(4));
System.out.println("the ~4 is " + Integer.toBinaryString(~4));
------------------------------------------------------------------------------------------------
结果:the 4 is 100
the ~4 is 11111111111111111111111111111011
5、位异或
// 位非^(1^1=0 1^0=1 0^0=0)
System.out.println("the 4 is " + Integer.toBinaryString(4));
System.out.println("the 6 is " + Integer.toBinaryString(6));
System.out.println("the 4 ^ 6 is " + Integer.toBinaryString(4 ^ 6));
------------------------------------------------------------------------------------------------
结果:the 4 is 100
the 6 is 110
the 4 ^ 6 is 10
6、左移和右移
// 有符号左移 << 有符号的右移 >> 无符号的右移 >>>
System.out.println("the 44 >> 2 is " + Integer.toBinaryString(4 >> 2));
System.out.println("the 44 << 2 is " + Integer.toBinaryString(4 << 2));
System.out.println("the 44 >>> 2 is " + Integer.toBinaryString(4 >>> 2));
------------------------------------------------------------------------------------------------
结果:the 4 >> 2 is 1
the 4 << 2 is 10000
the 4 >>> 2 is 1
7、补充知识
取模操作 a % (z^n) 等价于 a & (2^n - 1)
System.out.println("the 345 % 16 is " + Integer.toBinaryString(345 % 16));
System.out.println("the 345 & (16 - 1) is " + Integer.toBinaryString(345 & (16 - 1)));
------------------------------------------------------------------------------------------------
结果:the 345 % 16 is 1001
the 345 & (16 - 1) is 1001