Reading a short byte

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

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 works fine until this relatively large value appears.

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

      

25A equals 602 but prints len = 90 (5A). So why doesn't it read 0x02?

Sorry, I had to add an extra set of parentheses in my function. The solution was:short read = (short)(((getBytes()[0] & 0xff) << 8) + (getBytes()[1] & 0xff))

+3


source to share


1 answer


You can use DataInputStream

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 (expected)

tab=2, color=5, len=602

      

+2


source







All Articles