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

我有一个字节[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(); } 

你可以使用ByteBuffer,或者你可以用老式的方式:

 long result = 0x00FF & byteData[0]; result <<= 8; result += 0x00FF & byteData[1]; result <<= 8; result += 0x00FF & byteData[2]; result <<= 8; result += 0x00FF & byteData[3];