[英]Java: Convert byte to integer
I need to convert 2 byte array ( byte[2] ) to integer value in java. 我需要在java中将2字节数组(byte [2])转换为整数值。 How can I do that?
我怎样才能做到这一点?
You can use ByteBuffer
for this: 您可以使用
ByteBuffer
:
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort();
See also Convert 4 bytes to int . 另请参见将4个字节转换为int 。
In Java, Bytes are signed, which means a byte's value can be negative, and when that happens, @MattBall's original solution won't work. 在Java中,Bytes是有符号的,这意味着一个字节的值可能是负数,当发生这种情况时,@ MattBall的原始解决方案将无效。
For example, if the binary form of the bytes array are like this: 例如,如果bytes数组的二进制形式如下:
1000 1101 1000 1101
1000 1101 1000 1101
then myArray[0] is 1000 1101
and myArray[1] is 1000 1101
, the decimal value of byte 1000 1101
is -115
instead of 141(= 2^7 + 2^3 + 2^2 + 2^0) 那么myArray [0]是
1000 1101
而myArray [1]是1000 1101
,字节1000 1101
的十进制值是-115
而不是141(= 2 ^ 7 + 2 ^ 3 + 2 ^ 2 + 2 ^ 0)
if we use 如果我们使用
int result = (myArray[0] << 8) + myArray[1]
the value would be -16191
which is WRONG. 值为
-16191
,这是错误的。
The reason why its wrong is that when we interpret a 2-byte array into integer, all the bytes are unsigned, so when translating, we should map the signed bytes to unsigned integer: 其错误的原因在于,当我们将2字节数组解释为整数时,所有字节都是无符号的,因此在转换时,我们应该将带符号的字节映射到无符号整数:
((myArray[0] & 0xff) << 8) + (myArray[1] & 0xff)
the result is 36237
, use a calculator or ByteBuffer to check if its correct(I have done it, and yes, it's correct). 结果是
36237
,使用计算器或ByteBuffer检查它是否正确(我已经完成了,是的,它是正确的)。
Also, if you can use the Guava library: 另外,如果您可以使用Guava库:
Ints.fromByteArray(0, 0, myArray[1], myArray[0]);
It was worth mentioning since a lot of projects use it anyway. 值得一提的是,因为很多项目无论如何都会使用它。
Simply do this: 只需这样做:
return new BigInteger(byte[] yourByteArray).intValue();
Works great on Bluetooth command conversions etc. No need to worry about signed vs. unsigned conversion. 在蓝牙命令转换等方面效果很好。无需担心已签名和无符号转换。
Well, each byte is an integer in the range -128..127, so you need a way to map a pair of integers to a single integer. 好吧,每个字节都是-128..127范围内的整数,所以你需要一种方法将一对整数映射到一个整数。 There are many ways of doing that, depending on what you have encoded in the pair of bytes.
有很多方法可以做到这一点,具体取决于您在字节对中编码的内容。 The most common will be storing a 16-bit signed integer as a pair of bytes.
最常见的是将16位有符号整数存储为一对字节。 Converting that back to an integer depends on whether you store it big-endian form:
将其转换回整数取决于您是否将其存储为big-endian形式:
(byte_array[0]<<8) + (byte_array[1] & 0xff)
or little endian: 或小端:
(byte_array[1]<<8) + (byte_array[0] & 0xff)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.