This is because it actually performs promotion to int , which leaves a lot of “1” bits. Then you are shifted to the right, leaving the leftmost 2 bits equal to 0, but then ignoring those leftmost bits, discarding the bytes.
This becomes clearer when you highlight operations:
public class Test { public static void main(String[] args) { byte bar = -128; int tmp = (bar & ((byte)-64)) >>> 6; byte foo = (byte)tmp; System.out.println(tmp); System.out.println(foo); } }
prints
67108862 -2
So, repeat your bit arithmetic:
initial = 0b10000000 (-128) -64 = 0b11000000 initial & -64 = 0b11111111111111111111111110000000
Even if you get the correct result from and the operation (by casting at this point), >>> will first support the first operand of int .
EDIT: The solution is to change how you mask things. Instead of masking at -64, masks instead of 128 + 64 = 192 = 0xc0 instead:
byte foo = (byte)((bar & 0xc0) >>> 6);
That way, you really only get the two bits you want, instead of having a load of 1 s in the most significant 24 bits.
source share