The reason is the expansion of the sign associated with numerical advertising to int , which occurs when the bits are shifted. Before the shift, the value of varB increased to int . An unsigned bit shift to the right occurs, but its effects are discarded when returning to byte , which saves only the last 8 bits:
varB (byte) : 11111111 promoted to int : 11111111 11111111 11111111 11111111 shift right 6 : 00000011 11111111 11111111 11111111 cast to byte : 11111111
You can use the bitwise and operator & to mask unwanted bits before wrapping. Bitting with 0xFF contains only the 8 least significant bits.
varB = (byte) ((varB & 0xFF) >>> 6);
Here's what is happening now:
varB (byte) : 11111111 promoted to int : 11111111 11111111 11111111 11111111 bit-and mask : 00000000 00000000 00000000 11111111 shift right 6 : 00000000 00000000 00000000 00000011 cast to byte : 00000011
source share