为什么(-1>>32)=-1?
可能的重复:
为什么 1>>32 == 1?
-1 作为 int 转换为二进制,由 32 个 1 表示。 当我右移 31 次时,我得到 1(31 个 0 和 1 个 1)。 但是当我右移 32 次时,我再次得到 -1。 不应该等于0吗?
Possible Duplicate:
why is 1>>32 == 1?
-1 as an int converted to binary is represented by 32 1's.
When I right-shift it 31 times, I get 1 (31 0's and one 1).
But when I right-shift it 32 times, I get -1 again.
Shouldn't it be equal to 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Java 规范解释了移位运算符如下:
32 & 的值0x1f 为零。
如果左操作数是
long
,那么右操作数会得到一个额外的位,将上限扩展到 63 而不是 31。为了获得从 -1 向右移位的任何特定期望值,您需要指定整数的底层二进制表示形式(例如,二进制补码)以及位数(例如,32)。每种编程语言都可以对它们进行不同的定义,但为了使实现更简单,它们通常会指定不允许移位超过可用位数。这通常是因为底层 CPU 硬件也不支持它。毕竟,如果您想移动那么多位,则左侧操作数不再重要,因为结果始终是相同的。
The Java specification explains the shift operators as follows:
The value of
32 & 0x1f
is zero.If the left operand is
long
, then you get an extra bit for the right operand, expanding the upper limit to 63 instead of 31.In order to have any specific expected value from shifting -1 to the right, you need to specify the underlying binary representation of integers (e.g., two's complement) as well as the number of bits (e.g., 32). Each programming language can define those differently, but in the interest of keeping things simpler for the implementation, they'll usually specify that shifting by more than the number of available bits is not allowed. That's often because the underlying CPU hardware doesn't support it, either. After all, if you want to shift that many bits, the left operand no longer matters since the result will always be the same.