Search code examples
javaarraysshort

Reading short from byte array


Looking for a solution to why my readShort function won't properly read this number (602).

byte array contains: 0x02 0x05 0x02 0x5A

byte tab = pkt.read(); //successfully reads 2
byte color = pkt.read(); //successfully reads 5
short len = pkt.readShort(); //problem

My readShort function, which has been working fine until this relatively large value came up.

public short readShort() {
    short read = (short)((getBytes()[0] << 8) + getBytes()[1] & 0xff);
    return read;
}

25A is 602, but it's printing that len = 90 (5A). So why is it not reading the 0x02?

Sorry I ended up needing an extra set of parenthesis in my function. Solution was: short read = (short)(((getBytes()[0] & 0xff) << 8) + (getBytes()[1] & 0xff))


Solution

  • You could use a DataInputStream and something like

    byte[] bytes = new byte[] { 0x02, 0x05, 0x02, 0x5A };
    DataInputStream pkt = new DataInputStream(new ByteArrayInputStream(bytes));
    try {
        byte tab = pkt.readByte();
        byte color = pkt.readByte();
        short len = pkt.readShort();
        System.out.printf("tab=%d, color=%d, len=%d%n", tab, color, len);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Output is (your expected)

    tab=2, color=5, len=602