Ahsan Rafiq
Ahsan Rafiq

Reputation: 111

Logical right shift operator in java

I am beginner to java... I have tried very much but could not find the way the following line

System.out.println (-1>>>1);

gives 2147483647 ?

Can anyone help me ?

Upvotes: 0

Views: 369

Answers (2)

SamYonnou
SamYonnou

Reputation: 2068

This is because the binary representation of -1 is 11111111111111111111111111111111. When you perform an unsigned right bit-shift operation (>>>) on it it moves all of the bits right by the argument (1 in this case) and fills in empty spaces on the left with zeros so you get 01111111111111111111111111111111 which is the binary representation of Integer.MAX_VALUE = 2147483647 (not sure where you got 2147483648 from).

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499870

>>> is the bitwise right-shift operator, with 0 sign extension - in other words, all bits "incoming" from the left are filled with 0s.

-1 is represented by 32 bits which are all 1. When you shift that right by 1 bit with 0 sign extension, you end up with a value which has the 31 bottom bits still 1, but 0 for the top bit (the sign bit), so you end up with Integer.MAX_VALUE - which is 2147483647, not 2147483648 as your post states.

Or in JLS terms, from section 15.19:

The value of n >>> s is n right-shifted s bit positions with zero-extension, where:

If n is positive, then the result is the same as that of n >> s.

If n is negative and the type of the left-hand operand is int, then the result is equal to that of the expression (n >> s) + (2 << ~s).

If n is negative and the type of the left-hand operand is long, then the result is equal to that of the expression (n >> s) + (2L << ~s).

This definition ends up being a bit of a pain to work with - it's easier to just work with the "0 sign extension right-shift" explanation, IMO.

Upvotes: 1

Related Questions