对于Java中的整数,为什么-1为零填充右移1 = 2147483647? [英] Why is -1 zero fill right shift 1=2147483647 for integers in Java?
问题描述
对于以下程序:
public class ZeroFillRightShift
{
public static void main(String args[])
{
int x = -1;
int y = x>>>1;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
我得到如下输出:
x = -1
y = 2147483647
我得到的 -1>>>> 1
的结果是2147483647.如果它是必须移位的符号位,正如我所了解的那样,结果应该是1073741824.为什么2147483647呢?
The result that I got for -1>>>1
is 2147483647. If it’s the sign bit that has to be shifted, as I learned, the result should be 1073741824. Why is it 2147483647 then?
下图更清楚地说明了我的问题:
The following image illustrates my problem more clearly:
推荐答案
无符号右移运算符> >>将零移动到
最左边的位置,而>>后面的最左边位置取决于
符号扩展。
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
因此,-1向右移位一位,具有零扩展,这意味着它将在最左边的位置插入0。请记住,我们在这里处理两个补充:
So, -1 is shifted right one bit with zero-extension, which means it will insert a 0 into the leftmost position. Remember, we're dealing with two's complement here:
-1是: 11111111111111111111111111111111
或 0xFFFFFFFF
in Hex
-1 is: 11111111111111111111111111111111
or 0xFFFFFFFF
in Hex
-1 >>> 1是 01111111111111111111111111111111
或 0x7FFFFFFF
in Hex,< br>这是2 31 - 1 == 2147483647
-1 >>> 1 is 01111111111111111111111111111111
or 0x7FFFFFFF
in Hex,
which is 231 - 1 == 2147483647
这是移位运营商。
你似乎对两个补码感到困惑。 31位用于值,最左边的位用于符号。由于您只移位1位,因此有符号位变为0,这意味着为正,结果是最大正数,而 int
可以表示。
You seemed to be confused about two's complement. 31 bits are used for the value and the bit farthest to the left is used for the sign. Since you're only shifting by 1 bit, the signed bit becomes a 0, which means positive, and the result is the greatest positive number than an int
can represent.
也许另一个例子会有所帮助。让我们考虑以下内容:
Perhaps another example will help. Let's consider the following:
System.out.println(-2 >> 1); //prints -1
-2 = 11111111111111111111111111111110
如果我们使用签名的右移,我们得到: 11111111111111111111111111111111
,即-1。但是,如果我们这样做:
If we use a signed right shift, we get: 11111111111111111111111111111111
, which is -1. However, if we do:
System.out.println(-2 >>> 1); //prints 2147483647
,因为-2 = 11111111111111111111111111111110
并执行无符号右移,这意味着我们使用零扩展移位1位,给出: 01111111111111111111111111111111
since -2 = 11111111111111111111111111111110
and do an unsigned right shift, which means we shift by 1 bit with zero-extension, giving: 01111111111111111111111111111111
这篇关于对于Java中的整数,为什么-1为零填充右移1 = 2147483647?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!