8

我有一个 byte[4] 包含一个 32 位无符号整数(以大端序),我需要将其转换为 long(因为 int 不能保存无符号数)。

另外,我该如何做,反之亦然(即从包含 32 位无符号整数的 long 到字节 [4])?

4

3 回答 3

11

听起来像是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();
}
于 2012-03-24T20:04:56.210 回答
9

您可以使用 ByteBuffer,也可以使用老式的方法:

long result = 0x00FF & byteData[0];
result <<= 8;
result += 0x00FF & byteData[1];
result <<= 8;
result += 0x00FF & byteData[2];
result <<= 8;
result += 0x00FF & byteData[3];
于 2012-03-24T20:09:14.897 回答
1

Guava 具有处理无符号数值的有用类。

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/UnsignedInts.html#toLong(int )

于 2012-03-24T20:10:03.040 回答