3

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?

nKn
  • 13,691
  • 9
  • 45
  • 62
mechanikos
  • 771
  • 12
  • 32

3 Answers3

2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

this is how you can get the expected result

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

see dasblinkenlight's answer for details

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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.

barak manos
  • 29,648
  • 10
  • 62
  • 114