In Java, I have the following code:
byte lo = 0x88;
byte hi = 0x0;
short x = 0;
x |= lo;
x |= (short) ((short) hi << 8); // FIXME double cast ??
return x;
After the first operation, the value in the short is 0xff88
. I understand this is because Java does not support unsigned numbers.
How can I force it to ignore the sign? I'm not using this data directly in Java code so it shouldn't matter, right?
The sign is appearing when the byte is converted to an int prior to performing the bitwise operation. The conversion must sign extend the byte
value because byte
is a signed type in Java. The conversion must occur because bitwise operations are either operations on int
values or long
values.
There are two solutions:
Mask the top bits, either after the conversion to an int
, or after performing the bitwise OR; eg
x |= (lo & 0xff); x |= (hi & 0xff) << 8;
(It turns out that the masking is unnecessary for hi
... because of what you do later. However, the chances are that the JIT compiler will optimize away any unnecessary masking instructions. And if it doesn't, the overhead is so small that it it is unlikely to matter.)
Use Byte.toUnsignedInt(byte)
to convert the byte
to an int
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.