Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ByteBuffer switch endianness

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

like image 542
Constantine Avatar asked Nov 14 '14 12:11

Constantine


People also ask

What is the byte order of ByteBuffer?

By default, the order of a ByteBuffer object is BIG_ENDIAN. If a byte order is passed as a parameter to the order method, it modifies the byte order of the buffer and returns the buffer itself. The new byte order may be either LITTLE_ENDIAN or BIG_ENDIAN.

How do I find my ByteBuffer size?

After you've written to the ByteBuffer, the number of bytes you've written can be found with the position() method. If you then flip() the buffer, the number of bytes in the buffer can be found with the limit() or remaining() methods.

What is the most common endianness?

By far the most common ordering of multiple bytes in one number is the little-endian, which is used on all Intel processors.

What does ByteBuffer wrap do?

wrap. Wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity and limit will be array.


1 Answers

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

like image 95
Michael Lang Avatar answered Sep 21 '22 18:09

Michael Lang