我有一个 byte[4] 包含一个 32 位无符号整数(以大端序),我需要将其转换为 long(因为 int 不能保存无符号数)。
另外,我该如何做,反之亦然(即从包含 32 位无符号整数的 long 到字节 [4])?
我有一个 byte[4] 包含一个 32 位无符号整数(以大端序),我需要将其转换为 long(因为 int 不能保存无符号数)。
另外,我该如何做,反之亦然(即从包含 32 位无符号整数的 long 到字节 [4])?
听起来像是ByteBuffer的作品。
有点像
public static void main(String[] args) {
byte[] payload = toArray(-1991249);
int number = fromArray(payload);
System.out.println(number);
}
public static int fromArray(byte[] payload){
ByteBuffer buffer = ByteBuffer.wrap(payload);
buffer.order(ByteOrder.BIG_ENDIAN);
return buffer.getInt();
}
public static byte[] toArray(int value){
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(value);
buffer.flip();
return buffer.array();
}
您可以使用 ByteBuffer,也可以使用老式的方法:
long result = 0x00FF & byteData[0];
result <<= 8;
result += 0x00FF & byteData[1];
result <<= 8;
result += 0x00FF & byteData[2];
result <<= 8;
result += 0x00FF & byteData[3];
Guava 具有处理无符号数值的有用类。