【发布时间】: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] & 0xff) << 8) + (getBytes()[1] & 0xff))
【问题讨论】:
-
这可能是也可能不是,但它可能是
getBytes()[0] << 8行。尝试将其更改为(getBytes()[0] & 0xff) << 8。 -
我试过了,但它仍然说长度是 90。不管怎样,我修好了。我需要另一组括号。新代码很短 read = (short)(((getBytes()[0] & 0xff)
-
(short)(((short)getBytes()[0]) << 8)