Question

I have this code:

int i = 255;
byte b = (byte) i;
int c;
System.out.println(Integer.toBinaryString( i));
System.out.println("b = " + b); // b = -1
c=b>>>1;
System.out.println(Integer.toBinaryString( c));
System.out.println(c);

But I can't understand how it works. I think that unsigned shifting to 255(11111111) should give me 127(0111111) but it doesn't. Is my assumption wrong?

Was it helpful?

Solution

Shift operators including >>> operate on ints. The value of b, which is -1 because byte is signed, is promoted to int before the shift. That is why you see the results that you see.

The reason why 255 is re-interpreted as -1 is that 255 has all its eight bits set to one. When you assign that to a signed 8-bit type of byte, it is interpreted as -1 following two's complement rules.

OTHER TIPS

this is how you can get the expected result

c = (0xFF & b) >>> 1;

see dasblinkenlight's answer for details

Try this, and you will understand:

System.out.println(Integer.toBinaryString(i)); // 11111111
System.out.println(Integer.toBinaryString(b)); // 11111111111111111111111111111111
System.out.println(Integer.toBinaryString(c)); // 1111111111111111111111111111111

Variable int i equals 255, so the first print makes sense.

Variable byte b equals -1, because you store 255 in a single byte.

  • But when you call Integer.toBinaryString(b), the compiler converts b from byte to int, and (int)-1 == FFFFFFFFh == 11111111111111111111111111111111b, hence the second print.

Variable int c equals b>>>1, so the third print makes sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top