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

bit-shift, java

Solution

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`

Problem

For the program below: ``` 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); } ``` I get the output as follows: ``` x = -1 y = 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:

Original source