Why is -1 zero fill right shift 1=2147483647 for integers in Java?

元气小坏坏 提交于 2019-12-05 00:29:59

The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

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 is: 11111111111111111111111111111111 or 0xFFFFFFFF in Hex

-1 >>> 1 is 01111111111111111111111111111111 or 0x7FFFFFFF in Hex,
which is 231 - 1 == 2147483647

Here's a JLS reference for shift operators.

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

If we use a signed right shift, we get: 11111111111111111111111111111111, which is -1. However, if we do:

System.out.println(-2 >>> 1); //prints 2147483647

since -2 = 11111111111111111111111111111110 and do an unsigned right shift, which means we shift by 1 bit with zero-extension, giving: 01111111111111111111111111111111

The 32-bit decimal (two's complement) value -1 is 0xFFFFFFFF in hexadecimal. If you do an unsigned right shift ( >>>) by one bit on that you get 0x7FFFFFFF, which is 2147483647 decimal.

Your confusion arises from the (very common) misconception that there is a "sign bit" in 2s-complement intergers. It isn't. The left most bit, also known as the most significand bit (MSB) actively contributes to the value of the number.

In 2s complement notation, this bit merely indicates the sign of the number. But manipulation of that bit does not simply change the sign.

Another noteworthy property of the machine internal int format is that you don't need to interpret them as signed numbers. In fact, this is exactly what you do when you use the >>> operator: You interpret the number as unsingned number (notwithstanding the myth that "Java does not have unsigned integers"). Hence:

0xffffffff >>> 1 == 4294967295 / 2

and this is how your result makes sense. (Note that you can't write the above in Java source code, it will complain that the deciaml number is "out of range".)

Data types with true sign bits are IEEE floating point numbers.

The left-most bit in signed integer values are used to indicate weather the number is positive (0) or negative (1). -1 is represented as all bits on: 11111111111111111111111111111111. If you shift it left with >>>, you get 01111111111111111111111111111111 which is the highest positive number 2^31 - 1 = 2147483647

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!