将32位无符号整数(big endian)转换为long和back


问题内容

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

另外,我该如何做相反(即从包含32位无符号整数的long到byte [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();
}