【发布时间】:2012-04-08 22:49:12
【问题描述】:
我有一个 byte[4] 包含一个 32 位无符号整数(大端序),我需要将它转换为 long(因为 int 不能保存无符号数)。
另外,我该怎么做,反之亦然(即从包含 32 位无符号整数的 long 到 byte[4])?
【问题讨论】:
-
字节数组从何而来?
标签: java type-conversion endianness unsigned-integer
我有一个 byte[4] 包含一个 32 位无符号整数(大端序),我需要将它转换为 long(因为 int 不能保存无符号数)。
另外,我该怎么做,反之亦然(即从包含 32 位无符号整数的 long 到 byte[4])?
【问题讨论】:
标签: java type-conversion endianness unsigned-integer
听起来像是 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();
}
【讨论】:
int value = buffer.getInt();,那么 int 可能无法包含整个数字(如果它是未签名且未签名的)。
return buffer.getInt() & 0xFFFFFFFFL;,因为您将始终获得无符号值。 ByteBuffer 默认为 BIG_ENDIAN。您无需致电flip() 即可使用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];
【讨论】:
【讨论】: