为什么(-1>>32)=-1?

发布于 2024-10-14 16:01:48 字数 267 浏览 5 评论 0原文

可能的重复:
为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贵在坚持 2024-10-21 16:01:48

Java 规范解释了移位运算符如下:

如果左侧操作数的提升类型为int,则仅使用右侧操作数的最低 5 位作为移位距离。就好像右侧操作数受到按位逻辑 AND 运算符 & (§15.22.1),掩码值为 0x1f。因此,实际使用的移位距离始终在 0 到 31 的范围内(含)。

32 & 的值0x1f 为零。

如果左操作数是long,那么右操作数会得到一个额外的位,将上限扩展到 63 而不是 31。


为了获得从 -1 向右移位的任何特定期望值,您需要指定整数的底层二进制表示形式(例如,二进制补码)以及位数(例如,32)。每种编程语言都可以对它们进行不同的定义,但为了使实现更简单,它们通常会指定不允许移位超过可用位数。这通常是因为底层 CPU 硬件也不支持它。毕竟,如果您想移动那么多位,则左侧操作数不再重要,因为结果始终是相同的。

The Java specification explains the shift operators as follows:

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. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文