CKTIS / Java
ByteOrder — byte ordering
ByteOrder describes the byte ordering of multibyte values. Learn the difference between BIG_ENDIAN and LITTLE_ENDIAN and how to select data interpretation explicitly in ByteBuffer.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
import java.nio.ByteOrder;
ByteOrder big = ByteOrder.BIG_ENDIAN;
ByteOrder little = ByteOrder.LITTLE_ENDIAN;
buffer.order(big);
buffer.order(little);ByteOrder in java.nio represents the byte ordering of a multibyte value. In Java SE 21 it is a final class with constants, not a type declared with the enum keyword.
ByteOrder.BIG_ENDIAN puts the most significant byte first: 0x01020304 is stored as 01 02 03 04. ByteOrder.LITTLE_ENDIAN puts the least significant byte first: the same value is stored as 04 03 02 01. This concerns byte ordering, not bit ordering within a byte.
A new ByteBuffer uses BIG_ENDIAN. Calling buffer.order(...) selects the order for multibyte operations such as putInt and getInt; it does not rearrange bytes already stored. Thus, the example reads the same four bytes as two different numbers. Choose the order required by the file format or protocol. ByteOrder.nativeOrder() returns the hardware order, which need not match the data format.
Examples
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(0, 0x01020304);
System.out.print("bytes:");
for (int i = 0; i < 4; i++) {
System.out.print(" " + (buffer.get(i) & 0xFF));
}
System.out.println();
System.out.println("BIG_ENDIAN: " + buffer.getInt(0));
buffer.order(ByteOrder.LITTLE_ENDIAN);
System.out.println("LITTLE_ENDIAN: " + buffer.getInt(0));
}
}Result
bytes: 1 2 3 4 BIG_ENDIAN: 16909060 LITTLE_ENDIAN: 67305985
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.