No, you will not lose the 8th bit. But unfortunately, Java has two βfeaturesβ that make it more difficult than wise to deal with such values:
- all its primitive types are signed;
- when the primitive type is "decompressed" into another primitive type with a large size (for example, reading
byte to int , as is the case here), the sign bit of the "lower type" expands.
This means that, for example, if you read byte 0x80 , which is converted in binary format as:
1000 0000
when you read it as an integer, you get:
1111 1111 1111 1111 1111 1111 1000 0000 ^ This freaking bit gets expanded!
while you really wanted:
0000 0000 0000 0000 0000 0000 1000 0000
those. the integer value is 128. Therefore, you MUST mask it:
int b = array[0] & 0xff; 1111 1111 1111 1111 1111 1111 1000 0000 <-- byte read as an int, your original value of b 0000 0000 0000 0000 0000 0000 1111 1111 <-- mask (0xff) --------------------------------------- <-- anded, give 0000 0000 0000 0000 0000 0000 1000 0000 <-- expected result
Sad but true.
More generally: if you want to manipulate a lot of byte-oriented data, I suggest you take a look at ByteBuffer , it can help a lot. But, unfortunately, this will not save you from manipulating the bitmask, but simply simplifies reading a certain number of bytes as time (in the form of primitive types).
fge
source share