Home » Java » java – Reading Little Endian – LS Byte first for integer how to ignore the extra 0-Exceptionshub

java – Reading Little Endian – LS Byte first for integer how to ignore the extra 0-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have been reading these byte by bytes from streams. Example I read this line like this.

int payloadLength = r.readUnsignedShort();

The problem I have is that 2 bytes value is x3100 so it turns out to be 12544 but I suppose to only read as x31 which makes it to be only 49. How to ignore the extra 00.

How to&Answers:

Right shift the value by 8 bits and then and it with 0xFF. Right shifting moves the bits 8 bits to the right. Any other bits would also be moved to the right so you need to mask those of by do an ANDing (&) with 0xFF to get rid of them.


    int payloadLength = r.readUnsignedShort();

    payloadLength = (payloadLength >>> 8)& 0xFF;
    System.out.println(payLoadLength);

You may also want to swap the two bytes.

    v = 0xa0b;
    v = swapBytes(v);
    System.out.println(Integer.toHexString(v)); // 0xb0a


    public static int swapBytes(int v) {
        return ((v << 8)&0xFF00) | ((v >> 8) & 0xFF);
    }

Normally, for reading in just 16 bits you would not have to and it with 0xFF since the high order bits are 0’s. But I think it is a good practice and will prevent possible problems in the future.