publicstaticvoidmain(String[] args) { int i = -1; System.out.println("Before << , i's value is " + i); System.out.println("i's binary string is " + Integer.toBinaryString(i)); i <<= 10; System.out.println("After << , i's value is " + i); System.out.println("i's binary string is " + Integer.toBinaryString(i)); } 复制代码
Before << , i's value is -1 i's binary stringis11111111111111111111111111111111 After << , i's value is -1024 i's binary stringis11111111111111111111110000000000 复制代码
Before >> , i1's value is 4992 i1's binary stringis1001110000000 After >> , i1's value is 4 i1's binary stringis100 Before >> , i2's value is -4992 i2's binary stringis11111111111111111110110010000000 After >> , i2's value is -5 i2's binary stringis11111111111111111111111111111011 复制代码
Before >>> , i3's value is -4992 i3's binary stringis11111111111111111110110010000000 After >>> , i3's value is 4194299 i3's binary stringis1111111111111111111011 复制代码
真的懂了吗?
对 short、byte、char 的移位操作
再看如下例子:
1 2 3 4 5 6 7 8 9
publicstaticvoidmain(String[] args) { byte b = -1; System.out.println("Before >> , b's value is " + b); System.out.println("b's binary string is " + Integer.toBinaryString(b)); b >>>= 6; System.out.println("After >> , b's value is " + b); System.out.println("b's binary string is " + Integer.toBinaryString(b)); } 复制代码
Before >> , b's value is -1 b's binary stringis11111111111111111111111111111111 After >> , b's value is -1 b's binary stringis11111111111111111111111111111111 复制代码
publicstaticvoidmain(String[] args) { byte b = -1; System.out.println("Before >> , b's value is " + b); System.out.println("b's binary string is " + Integer.toBinaryString(b)); System.out.println("After >> , b's value is " + (b >>> 6)); System.out.println("b's binary string is " + Integer.toBinaryString(b >>> 6)); } 复制代码
在该例子中,没有使用 >>>= 对 b 进行再赋值,而是直接将 b >>> 6 进行输出(需要注意的是,b >>> 6 的结果为 int 类型),其输出如下:
1 2 3 4 5
Before >> , b's value is -1 b's binary stringis11111111111111111111111111111111 After >> , b's value is 67108863 b's binary stringis11111111111111111111111111 复制代码
Before >>> , i4's value is -1 i4's binary stringis11111111111111111111111111111111 After >>> 31 , i4's value is 1 i4's binary stringis1 After >>> 32 , i4's value is -1 i4's binary stringis11111111111111111111111111111111 After >>> 33 , i4's value is 2147483647 i4's binary stringis1111111111111111111111111111111 复制代码