ByteBuffer开关的字节序

君士坦丁

我正在尝试切换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);
}

main函数打印此二进制字符串:01111101 00000000 00000000 00000000但必须打印:00000000 10111110 00000000 00000000

迈克尔·朗(Michael Lang)

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

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

...

此外,字节序仅影响较大数值的字节顺序,而不影响此处解释的字节

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章