【问题标题】:Why in Java right-shifting 16 by 32 results in 16 and not 0? 16>>32 = 16 Why? [duplicate]为什么在 Java 中将 16 右移 32 得到 16 而不是 0? 16>>32 = 16 为什么? [复制]
【发布时间】: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


【解决方案1】:

Java Language Specification 状态

如果左侧操作数的提升类型是int只有五个 右手操作数的最低位用作移位 距离。 就好像右手操作数受到了 按位逻辑与运算符 & (§15.22.1) 与掩码值 0x1f (0b11111)。因此,实际使用的移动距离总是在 范围为 0 到 31(含)。

值 32 表示为

100000

最低 5 位是00000 所以0,移位了 0 位。

【讨论】:

猜你喜欢
  • 2011-04-05
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多