In Java, -4 >> 2 gives -1 but -5 >> 2 gives -2. Can anybody explain why? Here is a sample code:
byte r=-5;
r>>=2;
System.out.println(r);
Also in this scenario >> and >>> operators give the same answer. Can anyone explain that as well?
You can take a look at the bits. Using two's complement notation, the bits for -4
and -5
are, showing only the last 8 bits for brevity:
-4: 1111 1100
-5: 1111 1011
Bit shifting to the right 2 positions, with sign extension:
-4 >> 2: 1111 1111 (-1)
-5 >> 2: 1111 1110 (-2)
Normally, you think of >>>
not using sign extension, and this is true, but in this case:
r >>>= 2;
... the value r
is promoted to int
for the bit-shift operation using binary numeric promotion, but the compound assignment operator casts the returned value back to byte
, and the shifted-in zero "disappears".
byte r = -5; // 1111 1100
r >>>= -2; // promoted to int: 11111111 11111111 11111111 11111010
// bit shift: 00111111 11111111 11111111 11111110
// cast back to byte: 11111110 (-2)
The JLS, Section 15.26.2, talks about the casting operation done in compound assignment operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
That is, in this case, the result of the bit-shift is casted back to byte
.
The same cast-back-to-byte operation occurs when the value of r
is -4
.
Note that if the assignment part wasn't done, then you wouldn't see the same answer, because it wouldn't cast the result back to byte
:
System.out.println(r >>> 2);
Then you would see:
1073741822
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With