Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java byte order: LITTLE_ENDIAN and BIG_ENDIAN

Choose how `ByteBuffer` lays out multibyte values, use the same byte order to write and read them, and distinguish the buffer default from the platform’s native order.

Version: Java SE 21

Syntax

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

ByteBuffer big = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN);
ByteBuffer little = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);

ByteOrder.LITTLE_ENDIAN/BIG_ENDIAN refers to two public static final constants of type java.nio.ByteOrder. ByteOrder.LITTLE_ENDIAN puts the least significant byte first; ByteOrder.BIG_ENDIAN puts the most significant byte first. For the int value 0x01020304, the respective byte sequences are 04 03 02 01 and 01 02 03 04. Byte order does not change the order of bits inside a byte.

In Java SE 21, a new ByteBuffer starts in BIG_ENDIAN, including one created with wrap(byte[]). order() reports the current order; order(ByteOrder) changes the setting for that buffer without rearranging bytes already stored. ByteOrder.nativeOrder() reports the platform’s native order, not the buffer default. For a file or protocol, follow the format’s specified order rather than the hardware’s.

putInt(int) writes four bytes and getInt() reads four; both start at the current position and advance it by four. The byte-indexed overloads, putInt(int, int) and getInt(int), leave the position unchanged. Read in the same order used to write the data. If you read 04 03 02 01 as big-endian, you get 0x04030201 without an exception to warn you that the order is wrong.

Examples

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HexFormat;

public class ByteOrderDemo {
    public static void main(String[] args) {
        System.out.println("Default: " + ByteBuffer.allocate(4).order());
        roundTrip(ByteOrder.BIG_ENDIAN);
        roundTrip(ByteOrder.LITTLE_ENDIAN);
    }

    private static void roundTrip(ByteOrder order) {
        ByteBuffer writer = ByteBuffer.allocate(4).order(order);
        writer.putInt(0x01020304);
        byte[] bytes = writer.array();

        ByteBuffer reader = ByteBuffer.wrap(bytes).order(order);
        int decoded = reader.getInt();

        HexFormat hex = HexFormat.ofDelimiter(" ");
        System.out.println(order + ": " + hex.formatHex(bytes)
                + " -> 0x" + hex.toHexDigits(decoded));
    }
}

Result

Default: BIG_ENDIAN
BIG_ENDIAN: 01 02 03 04 -> 0x01020304
LITTLE_ENDIAN: 04 03 02 01 -> 0x01020304

The first line shows the default. In each round trip, `wrap(byte[])` creates a separate reader over the same array at position 0. With the matching order explicitly set, the reader recovers `0x01020304` from both byte layouts.

Related lessons

  • Java · Lesson 50 · Advanced · Version: 2

Sources