1

来自[隐藏链接--沦为恶意网站]

当要移位的值(左操作数)是 int 时,只有右手操作数的最后 5 位用于执行移位。移位的实际大小是被 31 (0x1f) 屏蔽的右侧操作数的值。即移位距离始终在 0 和 31 之间(如果移位值 > 32 移位为 32 % 值)

35             00000000 00000000 00000000 00100011
31 -> 0x1f     00000000 00000000 00000000 00011111
&              -----------------------------------
Shift value    00000000 00000000 00000000 00000011   -> 3

-29            11111111 11111111 11111111 11100011
31 -> 0x1f     00000000 00000000 00000000 00011111
&              -----------------------------------
Shift value    00000000 00000000 00000000 00000011   -> 3

那个的真实意义是什么?这是否意味着对于右移,您可以乘以 32 的最大值?这是为了防止溢出吗?

4

2 回答 2

2

这意味着您只能移动 0 到 31 之间的值,因为int类型中有 32 位。对于 along你只能移动 0 到 63 位。

如果您给它任何其他值,则移位量将被适当地& 31& 63适当地掩盖。

例如,如果你想要一个扩展数字的低 7 位的符号,你可以使用

n << -7 >> -7

无论nint_long


JLS 15.19

如果左侧操作数的提升类型是 int,则只有右侧操作数的五个最低位用作移位距离。就好像右手操作数经过位逻辑与运算符 & (§15.22.1) 与掩码值 0x1f。因此,实际使用的移位距离始终在 0 到 31 的范围内,包括 0 到 31。

If the promoted type of the left-hand operand is long, then only the six 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 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

于 2012-10-09T10:21:31.647 回答
2

It's not that the maximum you can multiply by is 32, it's 2^31. (Bit shifting is exponentiation, not multiplication)

Considering that integers only have 32 bits, what would you expect to happen if you shifted by more then 31 bits anyway? You'd end up with the exact same result regardless of your input value - all of its its bits would have been shifted "off the end" - so it would serve no purpose whatsoever as an operation.

于 2012-10-09T10:23:51.670 回答