简体   繁体   中英

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?

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

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 ad be the first through fourth bytes read. The value returned is:

 (((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)) 

The class file format itself is big-endian (or rather all multiple byte data in the class file is stored in such a way):

Class file format

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM