ByteBuffer Views And Byte Order

asIntBuffer and friends reinterpret the same bytes through the buffer ByteOrder: big- and little-endian views read different numbers.

JavaData Integrity

Code

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

public class ProtocolFrames {

    public static void main(String[] args) {
        ByteBuffer frame = ByteBuffer.allocate(8);
        frame.order(ByteOrder.BIG_ENDIAN); // writer lays out multi-byte fields big-endian
        frame.putInt(0x01020304);
        frame.putShort((short) 0x0506);

        frame.flip();
        byte[] head = new byte[4];
        frame.get(head); // relative read advances the position
        System.out.println("bytes: " + HexFormat.of().formatHex(head));

        // Views interpret the same bytes under the current ByteOrder
        frame.rewind();
        System.out.println("as big-endian int:    " + frame.getInt());
        ByteBuffer little = frame.duplicate().order(ByteOrder.LITTLE_ENDIAN);
        System.out.println("as little-endian int: " + little.getInt());
    }
}

How it works

ByteBuffer Views And Byte Order keeps everything in the class ProtocolFrames and the function main.

Applying it

Running the file prints labeled results such as bytes:, as big-endian int:, as little-endian int: — each operation’s effect is visible in the output.

Statements that matter

frame.order(ByteOrder.BIG_ENDIAN); // writer lays out multi-byte fields big-endian
frame.putInt(0x01020304);
ByteBuffer little = frame.duplicate().order(ByteOrder.LITTLE_ENDIAN);
frame.get(head); // relative read advances the position
System.out.println("bytes: " + HexFormat.of().formatHex(head));

Interactive Tools for This Topic

FAQ

What does ByteBuffer Views And Byte Order print when run?
No setup needed: run the file and look for labeled lines like `bytes:`, `as big-endian int:`, `as little-endian int:` in the output.