java 位操作 >>> 移位

标签 java int bit operation

为什么如果

int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31; 

我们有 00000000000000000000000000000001

但是如果

int x = -1
x = x >>> 32;

我们有 11111111111111111111111111111111(又是 -1)

但不是 00000000000000000000000000000000 吗?

最佳答案

来自 Section 15.19 of JLS :

If the promoted type of the left-hand operand is int, 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.

强调我的。所以:

x >>> n

相当于:

x >>> n & 0x1f  // or x >>> n % 32

因此,x >>> 32 等同于 x >>> 32 & 0x1f <==> x >>> 0 == x

因此经验法则是,每当您将数字移动 32(int32 位),你会得到相同的值。

关于java 位操作 >>> 移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817639/

相关文章:

c - 如何检查 8 位无符号字符中设置的位数?

java - TestNG:以编程方式运行测试 - 执行测试方法时 XmlTest 对象上设置的参数为空

java - eclipse(3.5 和 3.6)在 ubuntu 中崩溃

java - 在Java中根据种子创建一个随机整数数组

algorithm - 生成所有 n 位序列以及所有唯一的 k 位子序列。

scala - 为什么 chisel UInt(32.W) 不能取 bit[32] 恰好为 1 的无符号数?

java - 如何将 JLabel.getIcon() 转换为 BufferedImage

java - 如何在 Hippo CMS 模板中检查是否为空并显示富文本字段 (HTML)

java - 信用卡验证

c++ - 从指针到 uint32 的类型转换