<分区>
有人可以解释为什么以下按位表达式返回不同的结果吗:
System.out.println((-1<<31)<<1); // it prints 0
System.out.println(-1<<32); // it prints -1
<分区>
有人可以解释为什么以下按位表达式返回不同的结果吗:
System.out.println((-1<<31)<<1); // it prints 0
System.out.println(-1<<32); // it prints -1
最佳答案
-1<<32
相当于-1<<0
,即无操作。原因是移位距离(32)
与 0x1f
进行与运算和 32 & 0x1f
为 0。
这是在 JLS #15.19 中定义的(强调我的):
If the promoted type of the left-hand operand is int, then only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
关于Java 按位运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304960/