This may seem like an easy question, but I'm so confused.
byte[] bArray = new byte[]{(byte) (0x80 & 0xff)};
System.out.println(bArray[0]);
and my output is -128. Why?
How can I rewrite this so that the byte array contains 128?
I thought that the 0xff
made it unsigned.
Thanks for your help!
I thought that the 0xff made it unsigned.
Well, it does, sort of - it promotes it to an int
, and keeps just the last 8 bits.
However, you're then casting the result of that back to a byte
, and a byte
in Java is always signed. (It's annoying, but it's the way it is.) So you might as well just have written:
byte[] bArray = { (byte) 0x80 };
The result would be exactly the same.
You're storing the bit pattern you want to store (10000000) so if you're transmitting this elsewhere, you don't need to worry... it's just when you're viewing it as a byte
in Java that it's annoying.
See more on this question at Stackoverflow