Reputation: 151
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?
Upvotes: 5
Views: 1878
Reputation: 120486
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))
Upvotes: 5
Reputation: 2852
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
Upvotes: 8
Reputation: 2476
The class file format itself is big-endian (or rather all multiple byte data in the class file is stored in such a way):
All 16-bit, 32-bit, and 64-bit quantities are constructed by reading in two, four, and eight consecutive 8-bit bytes, respectively. Multibyte data items are always stored in big-endian order, where the high bytes come first.
But as mentioned by others, as a practical consideration you should almost never have to worry about this.
Upvotes: 2