Java 将两个字节读入一个整数?
我从文件中读取了一个Java 将两个字节读入一个整数?,java,integer,byte,bytearray,Java,Integer,Byte,Bytearray,我从文件中读取了一个byte[],我想从其中的两个字节中获取一个int。下面是一个例子: byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F}; int value = bytes.getInt(2,4); //This method doesn't exist 这将使值等于0x0110,或十进制的272。但显然,byte[].getInt()不存在。我怎样才能完成这项任务
byte[]
,我想从其中的两个字节中获取一个int
。下面是一个例子:
byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist
这将使值
等于0x0110
,或十进制的272
。但显然,byte[].getInt()
不存在。我怎样才能完成这项任务
上面的数组只是一个示例。我不知道实际值。您应该选择简单的:
int val = ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);
int val=((字节[2]&0xff)或者,您可以使用:
int val = (bytes[2] << 8) + bytes[3]
int val=(字节[2]尝试:
public static int getInt(字节[]arr,int off){
return arr[off]您可以使用ByteBuffer。它有您正在搜索的getInt方法和许多其他有用的方法这里有一个简单可靠的方法
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4);
// by choosing big endian, high order bytes must be put
// to the buffer before low order bytes
byteBuffer.order(ByteOrder.BIG_ENDIAN);
// since ints are 4 bytes (32 bit), you need to put all 4, so put 0
// for the high order bytes
byteBuffer.put((byte)0x00);
byteBuffer.put((byte)0x00);
byteBuffer.put((byte)0x01);
byteBuffer.put((byte)0x10);
byteBuffer.flip();
int result = byteBuffer.getInt();
GoogleBase16类来自Guava-14.0.1
new BigInteger(com.google.common.io.BaseEncoding.base16().encode(bytesParam),16).longValue();
答案之所以有效,是因为字节被提升为整数,以防这会给您造成理解上的困难。“字节[2]*256”不适合放在一个字节中,但这不是问题,因为“256”是一个整数,等等。可能是[Convert 4 bytes to int]()的重复,理想情况下应该是这样的(b1为什么0xff
?换句话说,bytes[0]有什么区别?否:如果bytes[2]大于0x7f,它将返回一个负整数。paxdiablo的答案中的“&0xff”是必需的。这是一个很好的解释。对于同样的事情,但有符号的值,我使用了:返回arr[off]
new BigInteger(com.google.common.io.BaseEncoding.base16().encode(bytesParam),16).longValue();