Open In App

java.nio.ByteOrder Class in Java

ByteOrder is a class from java.nio package. In general Byte Order mean the enumeration of ByteOrder.

Note: ByteOrder Class extends Object Class which is the root of the class hierarchy.



There are two fields of ByteOrder class

Field Description
BIG_ENDIAN This is a field that will be denoting big-endian byte order.
LITTLE_ENDIAN This is a field that will be Constant denoting little-endian byte order.

Syntax: Class declaration



public final class ByteOrder extends Object {}

Methods of this class are as follows:

Methods Description
nativeOrder()

This method is defined to increase the performance of JVM by allocating direct buffer in the same order to the JVM.

This method returns the native byte order of the hardware upon which this Java virtual machine is running.

toString() This method returns the string which is defined in a specified way.

Implementation:

Example




// Java Program to demonstrate ByteOrder Class
  
// Importing input output and utility classes
import java.io.*;
  
// Importing required classes from java.nio package
// for network linking
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Here object is created and allocated and
        // it with 8 bytes of memory
        ByteBuffer buf = ByteBuffer.allocate(8);
  
        // This line of code prints the os order
        System.out.println("OS Order         :- "
                           + ByteOrder.nativeOrder());
  
        // This line of code prints the ByteBuffer order
        // Saying that whether it is in BIG_ENDIAN or
        // LITTLE_ENDIAN
        System.out.println("ByteBuffer Order :- "
                           + buf.order());
  
        // Here the conversion of int to byte takes place
        buf.put(new byte[] { 13, 17, 21, 25 });
  
        // Setting the bit set to its complement using
        // flip() method of Java BitSet class
        buf.flip();
  
        IntBuffer integerbuffer = buf.asIntBuffer();
  
        System.out.println("{" + integerbuffer.position()
                           + " : " + integerbuffer.get()
                           + "}");
  
        integerbuffer.flip();
  
        buf.order(ByteOrder.LITTLE_ENDIAN);
  
        integerbuffer = buf.asIntBuffer();
  
        System.out.println("{" + integerbuffer.position()
                           + " : " + integerbuffer.get()
                           + "}");
    }
}

Output
OS Order         :- LITTLE_ENDIAN
ByteBuffer Order :- BIG_ENDIAN
{0 : 219223321}
{0 : 420811021}

Note:

  • The order of a newly-created byte buffer is always BIG_ENDIAN.
  • One can have different OS Order for different machines.

Article Tags :