Why -2>>>1 equals 2147483647 in Java

277 Views Asked by At

-2's one's complement is 100000...01

-2's two's complement is 1000000...10

-2 >>> 1 

According >>> definition left side shifts in 0

should be something like 01000......1, why becomes 0111111..11?

1

There are 1 best solutions below

0
On BEST ANSWER

In order to produce two's complement representation of 2 (i.e. -2's representation) you start with the representation of 2, flip all its bits, and add 1 to the result:

00000000000000000000000000000010 -- This is 2
11111111111111111111111111111101 -- This the inverse of 2
11111111111111111111111111111110 -- This is the inverse of 2, plus 1

-2's binary representation is 11111111111111111111111111111110 (demo).

Shifting it over to the right by one without sign-extension produces

01111111111111111111111111111111

which is precisely the result that you get.