Java bitshift strangeness

Posted by Martin on Stack Overflow See other posts from Stack Overflow or by Martin
Published on 2010-01-31T20:36:11Z Indexed on 2010/05/03 2:58 UTC
Read the original article Hit count: 458

Filed under:
|
|

Java has 2 bitshift operators for right shifts:

>> shifts right, and is dependant on the sign bit for the sign of the result

>>> shifts right and shifts a zero into leftmost bits

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

This seems fairly simple, so can anyone explain to me why this code, when given a value of -128 for bar, produces a value of -2 for foo:

byte foo = (byte)((bar & ((byte)-64)) >>> 6);

What this is meant to do is take an 8bit byte, mask of the leftmost 2 bits, and shift them into the rightmost 2 bits. Ie:

initial = 0b10000000 (-128)
-64 = 0b11000000
initial & -64 = 0b10000000
0b10000000 >>> 6 = 0b00000010

The result actually is -2, which is

0b11111110

Ie. 1s rather than zeros are shifted into left positions

© Stack Overflow or respective owner

Related posts about java

Related posts about bit-shift