6

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

Constantine
  • 1,802
  • 3
  • 23
  • 37

2 Answers2

15

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

Community
  • 1
  • 1
Michael Lang
  • 3,902
  • 1
  • 23
  • 37
  • Thanks Michael. I have totally forgot that endianness take effect only when you push multi-byte type in buffer. – Constantine Nov 14 '14 at 14:41
0

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

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