【问题标题】:ByteBuffer switch endiannessByteBuffer 切换字节顺序
【发布时间】:2026-02-04 21:45:01
【问题描述】:

我正在尝试切换 ByteBuffer 的字节序,但没有任何效果。做错了什么? 也许我的调试主函数不正确?

@Override
public byte[] toBytes(BigDecimal type) {
    int octets = getOctetsNumber();
    BigInteger intVal = type.unscaledValue();

    byte[] temp = intVal.toByteArray();
    int addCount = octets - temp.length;

    //        DEBUG
    ByteBuffer buffer = ByteBuffer.allocate(octets);
    for(byte b: intVal.toByteArray()){
        buffer.put(b);
    }
    if (addCount > 0){
        for (; addCount > 0; addCount--) {
            buffer.put((byte)0x00);
        }
    }
    buffer.flip();

    buffer.order( ByteOrder.BIG_ENDIAN);

    return buffer.array();
}

public static void main(String[] arg) {
    IntegerDatatype intVal = new IntegerDatatype(17);
    BigDecimal bd = new BigDecimal(32000);

    byte[] bytes = intVal.toBytes(bd);
    String out = new String();
    for (byte b : bytes) {
        out += Integer.toBinaryString(b & 255 | 256).substring(1) + " ";
    }
    System.out.println(out);
}

主函数打印这个二进制字符串:01111101 00000000 00000000 00000000 但必须打印:00000000 10111110 00000000 00000000

【问题讨论】:

    标签: java endianness


    【解决方案1】:

    在将值放入缓冲区之前,您需要更改字节顺序。 只需在分配缓冲区大小后立即移动该行就可以了。

    //        DEBUG
    ByteBuffer buffer = ByteBuffer.allocate(octets);
    buffer.order( ByteOrder.BIG_ENDIAN);
    for(byte b: intVal.toByteArray()){
        buffer.put(b);
    }
    

    ...

    此外,字节序只影响较大数值的字节顺序,而不是here解释的字节

    【讨论】:

    • 谢谢迈克尔。我完全忘记了字节序只有在你在缓冲区中推送多字节类型时才会生效。
    【解决方案2】:

    应在创建缓冲区后立即设置,请参阅

    http://www.javamex.com/tutorials/io/nio_byte_order.shtml

    【讨论】: