Java:将字节转换为整数
我需要在java中将2字节数组(字节[2])转换为整数值。我如何才能做到这一点?您可以使用:Java:将字节转换为整数,java,Java,我需要在java中将2字节数组(字节[2])转换为整数值。我如何才能做到这一点?您可以使用: ByteBuffer buffer = ByteBuffer.wrap(myArray); buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian int result = buffer.getShort(); 另请参见。嗯,每个字节都是-128..127范围内的整数,因此需要一种将一对整数映射为单个整数的方法。有很多方
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort();
另请参见。嗯,每个字节都是-128..127范围内的整数,因此需要一种将一对整数映射为单个整数的方法。有很多方法可以做到这一点,这取决于您在字节对中编码的内容。最常见的是将16位有符号整数存储为一对字节。将其转换回整数取决于是否以大端形式存储:
(byte_array[0]<<8) + (byte_array[1] & 0xff)
(byte_array[0]在Java中,字节是有符号的,这意味着字节的值可以是负数,当这种情况发生时,@MattBall的原始解决方案将无法工作
例如,如果字节数组的二进制形式如下所示:
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]如果您可以使用Guava库:
Ints.fromByteArray(0, 0, myArray[1], myArray[0]);
值得一提的是,很多项目都使用它。只需这样做:
return new BigInteger(byte[] yourByteArray).intValue();
在蓝牙命令转换等方面效果很好。无需担心有符号和无符号转换。这个问题需要一些澄清。现在,我们只看你选择哪个答案的意思。谢谢你,这很有效。ByteBuffer会处理有符号和无符号字节吗?@keshav:什么意思?没有“有符号”或“无符号”字节。一个字节只是一组0
s和1
s;唯一的意义在于如何解释这些数字。@Matt:一旦转换完成,如果转换后的数字是负数(比如-100),我会将其视为-100吗?@keshav:我测试了它。ByteBuffer
将正确处理此问题。也就是说,如果字节表示负数,则此代码将输出负数int
。演示:和。记住,只有最重要(最左边)的字节才是负数位为1
。这不起作用,因为+
的优先级高于注意,此类中有一个构造函数,您可以在其中手动指定要处理无符号值。
import java.io.*;
public class ByteArray {
public static void main(String[] args) throws IOException {
File f=new File("c:/users/sample.txt");
byte[]b={1,2,3,4,5};
ByteArrayInputStream is=new ByteArrayInputStream(b);
int i;
while((i=is.read())!=-1) {
System.out.println((int)i);
FileOutputStream f1=new FileOutputStream(f);
FileOutputStream f2=new FileOutputStream(f);
ByteArrayOutputStream b1=new ByteArrayOutputStream();
b1.write(6545);
b1.writeTo(f1);
b1.writeTo(f2);
b1.close();
}
import java.io.*;
public class ByteArray {
public static void main(String[] args) throws IOException {
File f=new File("c:/users/sample.txt");
byte[]b={1,2,3,4,5};
ByteArrayInputStream is=new ByteArrayInputStream(b);
int i;
while((i=is.read())!=-1) {
System.out.println((int)i);
FileOutputStream f1=new FileOutputStream(f);
FileOutputStream f2=new FileOutputStream(f);
ByteArrayOutputStream b1=new ByteArrayOutputStream();
b1.write(6545);
b1.writeTo(f1);
b1.writeTo(f2);
b1.close();
}