Saturday, February 20, 2010

Endianness of Java

In Java, multibyte data items or streams are stored in big endian order.


Using Java to write bytes directly to the wire will require byte-order transformation if the recipient talks in little endian. The same is true if you are reading directly from the wire from a sender who talks in little endian.


If you are using a byte array wrapped in ByteBuffer,



byte[] data = new byte[] { 12, 19, 83, 05, -05, 55, -55 };
ByteBuffer byteBuffer = ByteBuffer.wrap(data);

Transforming from big endian to little endian is easy,



byteBuffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);

If you are unsure of the endianness of the underlying platform, just invoke the native order method.



java.nio.ByteOrder.nativeOrder();

Aside from streams, operands in classes that are above 1 byte in size are in big endian order.

No comments: