为什么是(-1>>> 32)= -1? [英] Why is (-1 >>> 32) = -1?

查看:130
本文介绍了为什么是(-1>>> 32)= -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  为什么1>> 32 == 1?

-1为int转换为二进制是32 1的psented重新$ P $。
当我31次右移它,我得到1(31 0和一个1)。
但是,当我32次右移,我得-1一次。
难道不应该等于0?

-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?

推荐答案

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

The Java specification explains the shift operators as follows:

如果左侧操作数的提升的类型为 INT ,只有右手操作的五个最低阶位被用作移位距离。这是因为如果右手操作体进行按位逻辑AND运算符&安培; §15.22.1)与屏蔽值 0x1F的。因此实际所用的偏移距离总是在0至31范围,包括

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.

32安培的价值;为0x1F 是零。

如果左操作数,那么你会得到正确的操作数额外位,扩大了上限到63,而不是31。

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.

为了从转移-1到右侧有什么具体的预期值,则需要指定底层的二进制重新$ P $整数psentation(如补),以及位(如,32号)。每种编程语言可以定义不同的,但在保持事情变得更简单的实现的利益,他们通常会指定超过可用的位数转移是不允许的。这往往是因为底层的CPU硬件不支持它,无论是。毕竟,如果你想很多位移位,左操作不再是问题,因为其结果将始终是相同的。

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.

这篇关于为什么是(-1>>> 32)= -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆