【发布时间】:2014-11-06 16:45:44
【问题描述】:
我在 Java 中使用右移运算符时遇到了一个看起来很奇怪的情况。当我将 16 右移 31 时,结果为 0,但是在尝试将 16 右移 32 时,它本身仍然是 16。有人可以解释一下吗,因为我为此发疯了。
public class RightShiftTest {
public static void main(String args[]) {
int b = 16;
System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));
// As expected it is 0
System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));
// But why is it not 0 but 16
System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32));
}
}
Output:
Bit pattern for int 16 is 10000
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000
【问题讨论】:
-
简单的谷歌搜索可以给你答案。
-
问:“为什么语言 X 做 Y 的方式是这样的?”答:因为规范是这样说的。
-
好吧,常识妨碍了我,所以我没有想到检查规范,它说:(16>>1) 32 次将获得与 (16>>32) 相同的结果一次.
-
这是一个合理的问题。事实上,我认为这是一个很好的问题,也是对 SO 有用的问答参考材料。无论如何,这是无论如何只是询问轮班操作员如何工作的问题的重复,而不是链接问题的答案之一甚至接近解释这种行为。然而,这里给出的答案完美地解释了这一点。
标签: java