Moving bits to left

    byte right =0xf; // 00001111
    System.out.println(Integer.toBinaryString(right)); // 00001111

    right = (byte)(right << 4);
    System.out.println(Integer.toBinaryString(right)); // 11111111111111111111111111110000

why right is equal to 11111111111111111111111111110000? I explicitly cast it to byte = 8 bits.

I'm excpecting for an output: 11110000.

Jon Skeet
people
quotationmark

If you hadn't cast to byte, all would be well.

There are no shift operators defined for byte, so the value is first promoted to int - which is fine, and still 0000[...]1111.

You then shift left 4 bits, giving 0000[...]111000.

You then cast to byte, giving a byte of 11110000.

You then call Integer.toBinaryString, which takes an int parameter. That means the byte 1111000 is convert to int - at which point it's sign-extended to 11111111111111111111111111110000 (as per JLS 5.1.2), which is then printed.

Options:

  • Don't cast down to byte, so you don't end up with a conversion back to int. (e.g. use int shifted = right << 4; and then pass shifted into Integer.toBinaryString.)
  • Instead of leaving the conversion implicit, use right & 0xff to apply a bit-mask so you can only have the bottom 8 bits set.

Either of those prints 11110000 instead.

people

See more on this question at Stackoverflow