Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and endianness

How does java take care of endianness? In case if you are moving your application from a little endian to a big endian or vice versa. How are the data members or properties of class affected?

like image 669
JavaUSer Avatar asked Dec 09 '22 04:12

JavaUSer


2 Answers

The Java virtual machine abstracts this consideration away, such that you should not need to worry about it as long as you are working entirely within Java. The only reason you should have to consider byte order is if you are communicating with a non-java process, or something similar.

Edit: edited for clarity of wording

like image 104
nonVirtualThunk Avatar answered Dec 11 '22 16:12

nonVirtualThunk


If you are mapping a buffer of a larger type over a ByteBuffer then you can specify the endianness using the ByteOrder values. Older core libraries assume network order.

From ByteBuffer:

Access to binary data

This class defines methods for reading and writing values of all other primitive types, except boolean. Primitive values are translated to (or from) sequences of bytes according to the buffer's current byte order, which may be retrieved and modified via the order methods. Specific byte orders are represented by instances of the ByteOrder class. The initial order of a byte buffer is always BIG_ENDIAN.

and ByteOrder provides access to the native order for the platform you're working on.

Compare that to the older DataInput which is not useful for interop with local native services:

Reads four input bytes and returns an int value. Let a-d be the first through fourth bytes read. The value returned is:

(((a & 0xff) << 24) | ((b & 0xff) << 16) |
 ((c & 0xff) << 8) | (d & 0xff))
like image 24
Mike Samuel Avatar answered Dec 11 '22 16:12

Mike Samuel