【问题标题】:Reading short from byte array从字节数组中读取短
【发布时间】:2014-10-18 20:41:33
【问题描述】:

正在寻找解决我的 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] &amp; 0xff) &lt;&lt; 8) + (getBytes()[1] &amp; 0xff))

【问题讨论】:

  • 这可能是也可能不是,但它可能是getBytes()[0] &lt;&lt; 8 行。尝试将其更改为(getBytes()[0] &amp; 0xff) &lt;&lt; 8
  • 我试过了,但它仍然说长度是 90。不管怎样,我修好了。我需要另一组括号。新代码很短 read = (short)(((getBytes()[0] & 0xff)
  • (short)(((short)getBytes()[0]) &lt;&lt; 8)

标签: java bytearray short


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多