I have to convert bytes to signed/unsigned int or short.
The methods below are correct? Which is signed and which unsigned?
Byte order: LITTLE_ENDIAN
public static int convertTwoBytesToInt1(byte b1, byte b2) {
return (int) ((b2 << 8) | (b1 & 0xFF));
}
VS.
public static int convertTwoBytesToInt2(byte b1, byte b2) {
return (int) (( (b2 & 0xFF) << 8) | (b1 & 0xFF));
}
and
public static int convertFourBytesToInt1(byte b1, byte b2, byte b3, byte b4){
return (int) ((b4<<24)+(b3<<16)+(b2<<8)+b1);
}
VS.
public static int convertFourBytesToInt2(byte b1, byte b2, byte b3, byte b4){
return (int) (( (b4 & 0xFF) << 24) | ((b3 & 0xFF) << 16) | ((b2 & 0xFF) << 8) | (b1 & 0xFF));
}
I’m interested only in this conversion forms. Thanks!
The first method (
convertXXXToInt1()) of each pair is signed, the second (convertXXXToInt2()) is unsigned.However, Java
intis always signed, so if the highest bit ofb4is set, the result ofconvertFourBytesToInt2()will be negative, even though this is supposed to be the “unsigned” version.Suppose a
bytevalue,b2is -1, or 0xFF in hexadecimal. The<<operator will cause it to be “promoted” to aninttype with a value of -1, or 0xFFFFFFFF. After the shift of 8 bits, it will be 0xFFFFFF00, and after a shift of 24 bytes, it will be 0xFF000000.However, if you apply the bitwise
&operator, the higher-order bits will be set to zero. This discards the sign information. Here are the first steps of the two cases, worked out in more detail.Signed:
Unsigned: