从字节数组中读取短

时间:2014-10-18 20:41:33

标签: java bytearray short

寻找解决方案,说明为什么我的readShort函数无法正确读取此数字(602)。

字节数组包含: 0x02 0x05 0x02 0x5A

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

我的readShort函数,一直工作正常,直到出现这个相对较大的值。

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

25A是602,但打印的是len = 90(5A)。那么为什么不读取0x02?

抱歉,我的函数中最后需要一组额外的括号。 解决方案是:short read = (short)(((getBytes()[0] & 0xff) << 8) + (getBytes()[1] & 0xff))

1 个答案:

答案 0 :(得分:2)

您可以使用DataInputStream

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();
}

输出是(您的预期)

tab=2, color=5, len=602