我一直是这样搞的,代码不怎么好看,但能满足要求。字节最高位是1的时候识别为负数,是个麻烦。 public class A { public static void main(String[] args) { byte[] array = { (byte) 0x97, (byte) 0x51 }; int i = getByteInt(array[0]) * 256 + getByteInt(array[1]); System.out.println(i); } public static int getByteInt(byte b) { return b < 0 ? (256 + b) : b; } }
一个int是4 bytes
而且牵扯到big-endian vs little-endian
如果是big-endian:
byte[0] | byte[1] << 8 | byte[2] << 16 | byte[3] << 24
else if little-endian
byte[0] << 24 | byte[1] << 16 | byte[2] << 8 | byte[3]
如果不了解所在运行平台具体是那个,建议用字节数组流来进行转换
byte[] bytes=new byte[4];//int 占4字节
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
DataInputStream dis=new DataInputStream(bais);
int intValue=dis.readInt();
//写一个整数到byte数组中
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
dos.writeInt(intValue);
byte[] bytes=baos.toByteArray();
public class A { public static void main(String[] args) {
byte[] array = { (byte) 0x97, (byte) 0x51 };
int i = getByteInt(array[0]) * 256 + getByteInt(array[1]);
System.out.println(i);
} public static int getByteInt(byte b) {
return b < 0 ? (256 + b) : b;
}
}