Convert from 2 or 4 bytes to signed/unsigned short/int

后端 未结 2 1505
粉色の甜心
粉色の甜心 2020-12-31 21:57

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

<
2条回答
  •  [愿得一人]
    2020-12-31 22:55

    The first method (convertXXXToInt1()) of each pair is signed, the second (convertXXXToInt2()) is unsigned.

    However, Java int is always signed, so if the highest bit of b4 is set, the result of convertFourBytesToInt2() will be negative, even though this is supposed to be the "unsigned" version.

    Suppose a byte value, b2 is -1, or 0xFF in hexadecimal. The << operator will cause it to be "promoted" to an int type 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:

    byte b2 = -1; // 0xFF
    int i2 = b2; // 0xFFFFFFFF
    int n = i2 << 8; // 0x0xFFFFFF00
    

    Unsigned:

    byte b2 = -1; // 0xFF
    int i2 = b2 & 0xFF; // 0x000000FF
    int n = i2 << 8; // 0x0000FF00
    

提交回复
热议问题