测试 LITTLE_ENDIAN 和 BIG_ENDIAN 场景

Testing both LITTLE_ENDIAN and BIG_ENDIAN scenarios

如果我需要以不同方式处理 LITTLE_ENDIANBIG_ENDIAN 情况,如果我的系统使用 LITTLE_ENDIAN,我该如何测试 BIG_ENDIAN 情况?当系统的ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)时,你如何测试ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)的情况?因为 byteBuffer .order(ByteOrder.BIG_ENDIAN) 只是改变字节缓冲区的顺序,而不是系统,对吗?

使用ByteBuffer. It has method order(ByteOrder bo):

Modifies this buffer's byte order.

Parameters:
bo - The new byte order, either BIG_ENDIAN or LITTLE_ENDIAN

请注意 ByteBuffer 的 javadoc 说:

The initial order of a byte buffer is always BIG_ENDIAN.

例子

int value = 123456789;
byte[] bigEndian = ByteBuffer.allocate(Integer.BYTES)
        .order(ByteOrder.BIG_ENDIAN)
        .putInt(value)
        .array();
byte[] littleEndian = ByteBuffer.allocate(Integer.BYTES)
        .order(ByteOrder.LITTLE_ENDIAN)
        .putInt(value)
        .array();
System.out.printf("value = 0x%08x = %d%n", value, value);
System.out.println(Arrays.toString(bigEndian));
System.out.println(Arrays.toString(littleEndian));

输出

value = 0x075bcd15 = 123456789
[7, 91, -51, 21]
[21, -51, 91, 7]