Mat*_*all 24
你可以使用ByteBuffer这个:
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort();
Run Code Online (Sandbox Code Playgroud)
另请参见将4个字节转换为int.
Div*_*nto 10
在Java中,Bytes是有符号的,这意味着一个字节的值可能是负数,当发生这种情况时,@ MattBall的原始解决方案将无效.
例如,如果bytes数组的二进制形式如下:
1000 1101 1000 1101
然后myArray的[0]是1000 1101与myArray的[1] 1000 1101,字节的十进制值1000 1101是-115代替141(= 2 ^ 7 + 2 ^ 3 + 2 ^ 2 + 2 ^ 0)
如果我们使用
int result = (myArray[0] << 8) + myArray[1]
价值将-16191是错误的.
其错误的原因在于,当我们将2字节数组解释为整数时,所有字节都是无符号的,因此在转换时,我们应该将带符号的字节映射到无符号整数:
((myArray[0] & 0xff) << 8) + (myArray[1] & 0xff)
结果是36237,使用计算器或ByteBuffer来检查它是否正确(我已经完成了,是的,它是正确的).
| 归档时间: |
|
| 查看次数: |
46734 次 |
| 最近记录: |