Java - File Input Output Little endian

Byte Buffer and Its Byte Order

Big endian order stores significant bits first.

Little endian order stores least significant bits first.

For 00000001 00101100 is in the big endian byte order.

In the little endian byte order, it is 00101100 00000001.

Java uses a big-endian byte order to store data.

java.nio.ByteOrder class represents a byte order.

The following code shows how to get and set byte order for a byte buffer.

You use the order() method of the ByteBuffer class to get or set the byte order.

Demo

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

public class Main {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(2);
    System.out.println("Default Byte Order: " + bb.order());
    bb.putShort((short) 300);
    bb.flip();//from  ww  w  . java  2  s .  com
    showByteOrder(bb);

    // Repopulate the buffer in little endian byte order
    bb.clear();
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.putShort((short) 300);
    bb.flip();
    showByteOrder(bb);
  }

  public static void showByteOrder(ByteBuffer bb) {
    System.out.println("Byte Order: " + bb.order());
    while (bb.hasRemaining()) {
      System.out.print(bb.get() + "  ");
    }
    System.out.println();
  }
}

Result

Related Topic