ByteBuffer switch endianness
Asked Answered
E

2

7

I am trying to switch endianess of ByteBuffer, but there is no effects from it. What am doing wrong? Maybe my debug main function is incorrect?

@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 function prints this binary string : 01111101 00000000 00000000 00000000 but must prints: 00000000 10111110 00000000 00000000

Electrolyze answered 14/11, 2014 at 12:29 Comment(0)
L
17

You need to change the endianness before putting values into the buffer. Just move the line right after allocating the buffer size and you should be fine.

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

...

In addition, endianness does only impact the order of bytes of larger numeric values, not bytes as explained here

Lepido answered 14/11, 2014 at 12:37 Comment(1)
Thanks Michael. I have totally forgot that endianness take effect only when you push multi-byte type in buffer.Electrolyze
L
0

It should be set immediately after creating the buffer, please see

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

Losse answered 14/11, 2014 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.