Java中'&'与、'|'或、'^'异或、'<<'左移位、'>>'右移位
1 public static void main(String[] args) { 2 /* 3 * &:与运算 4 * 全为1则为1,否则为0 5 */ 6 System.out.print(1 & 0); 7 System.out.print("--"); 8 System.out.print(1 & 1); 9 System.out.print("--"); 10 System.out.println(0 & 0); 11 // out:0--1--0 12 13 /* 14 * |:或运算 15 * 全为0则为0,否则为1 16 */ 17 System.out.print(1 | 0); 18 System.out.print("--"); 19 System.out.print(1 | 1); 20 System.out.print("--"); 21 System.out.println(0 | 0); 22 // out:1--1--0 23 24 /* 25 * ^:异或运算 26 * 相同为0,不同为1 27 */ 28 System.out.print(1 ^ 0); 29 System.out.print("--"); 30 System.out.print(1 ^ 1); 31 System.out.print("--"); 32 System.out.println(0 ^ 0); 33 // out:1--0--0 34 }
关于'<<'与'>>'操作:
- m<<n,表示m二进制,右边尾部加0;
- m>>n,表示m二进制,右边尾部去掉1位;
- m>>>n,表示m二进制,忽略其符号位,从左至右,去掉最后的n位;
- 不存在'<<<';
1 public static void main(String[] args) { 2 int integer = 2; 3 printBinary(integer); 4 integer = 2 >> 1; 5 printBinary(integer); 6 integer = 2 >> 2; 7 printBinary(integer); 8 integer = 2 >> 3; 9 printBinary(integer); 10 System.out.println("===================="); 11 integer = 2 << 1; 12 printBinary(integer); 13 integer = 2 << 2; 14 printBinary(integer); 15 integer = 2 << 3; 16 printBinary(integer); 17 System.out.println("===================="); 18 integer = -2 << 1; 19 printBinary(integer); 20 System.out.println("===================="); 21 integer = -2 >> 1; 22 printBinary(integer); 23 System.out.println("===================="); 24 integer = 3 >> 1; 25 printBinary(integer); 26 System.out.println("===================="); 27 integer = -2; 28 printBinary(integer); 29 printBinary(integer>>>1); 30 printBinary(-integer); 31 printBinary(-integer>>>1); 32 } 33 private static void printBinary(Integer integer) { 34 System.out.println("Integer.toBinaryString()="+Integer.toBinaryString(integer)+", integer="+integer); 35 } 36 /** 37 Integer.toBinaryString()=10, integer=2 38 Integer.toBinaryString()=1, integer=1 39 Integer.toBinaryString()=0, integer=0 40 Integer.toBinaryString()=0, integer=0 41 ==================== 42 Integer.toBinaryString()=100, integer=4 43 Integer.toBinaryString()=1000, integer=8 44 Integer.toBinaryString()=10000, integer=16 45 ==================== 46 Integer.toBinaryString()=11111111111111111111111111111100, integer=-4 47 ==================== 48 Integer.toBinaryString()=11111111111111111111111111111111, integer=-1 49 ==================== 50 Integer.toBinaryString()=1, integer=1 51 ==================== 52 Integer.toBinaryString()=11111111111111111111111111111110, integer=-2 53 Integer.toBinaryString()=1111111111111111111111111111111, integer=2147483647 54 Integer.toBinaryString()=10, integer=2 55 Integer.toBinaryString()=1, integer=1 56 */
梦想要一步步来!