I’m a bit confused regarding a conversion from bytes to integers. Consider the following code:
byte[] data = new byte[] { 0, (byte) 0xF0 };
int masked = data[0] << 8 & 0xFF | data[1] & 0xFF; //240
int notMasked = data[0] << 8 | data[1]; //-16
Because bytes in java are signed, data[1] is not 240 decimal, but rather the 2’s complement, -16. However, it should still be, in binary: 0x11110000 so, why do I need to do data[1] & 0xFF ?
Is Java converting everything to Integer before passing it to the | operator? Why does &0xFF make a difference then?
Java bytes are signed (unfortunately) – so when you promote the value to an
intin order to perform the bitwise|, it ends up being sign-extended as0xFFFFFFF0. That then messes up the|withdata[0]. The masking with& 0xffconverts it to an integer value of 240 (just0x000000F0) instead.However, you’ve stlil got a problem. This code:
should be:
… otherwise you’re masking after the shift, which won’t work. I’ve added brackets because I’m never sure of the predence of
&,<<and|…