0

In Java I created a byte consisting of only 'on' bits, so:

    byte a = (byte) 0xff;
    System.out.println(a);

However, when this prints I get the result -1 instead of 255 (=15*16+15). I understand that the first bit in an integer is for the sign, but integers are 32 bit while this byte is only 8 bit.

If I use the following code, the expected results is given:

    byte a = (byte) 0xff;
    System.out.println(a & 0xff);

This really surprises me! How can a bitwise and operation of a byte with itself suddenly return a different result? Can anybody explain this effect?

Héctor van den Boorn
  • 1,218
  • 13
  • 32
  • Also, http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2, specifically: _A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format._ – Sotirios Delimanolis Jul 22 '15 at 21:30
  • Signed bytes strike again – harold Jul 22 '15 at 21:31
  • 1
    ...and specifically, you need to note that `a & 0xff` has a byte on one side and an int on the other, which is why the byte is being widened. – Powerlord Jul 22 '15 at 21:33
  • That doesn't fully explain why the second piece of code prints 255. What happens there is that because `0xff` is an `int` constant, `a` is cast to `int` too, using the widening conversion quoted, and due to the way two's complement works `-1 & 255` is `255`. – biziclop Jul 22 '15 at 21:33
  • Here's some more: http://stackoverflow.com/questions/19434366/signed-byte-type-and-bitwise-operators-in-java for promotion of operands. – Sotirios Delimanolis Jul 22 '15 at 21:35
  • 1
    As for why `(byte) 0xff` ends up being -1, https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.3 mentions that all bits not in the new type are just tossed out and that the sign may change because of this. int 255 is binary `11111111`, but in a byte binary `11111111` is -1. When you widen -1 back out to an int, all bytes are set to 1. – Powerlord Jul 22 '15 at 21:39
  • Why you do not try explicit type casting, by just adding "(int)". OR. as far I know, byte & int are two compatible types, and byte range is smaller than int, so you even not to use type casting. The language itself assign a byte value to an int variable. – Waqas Shabbir Jul 23 '15 at 05:01

0 Answers0