ByteBuffer order() method in Java with Examples
Last Updated :
17 Jun, 2019
order()
The order() method of java.nio.ByteBuffer class is used to retrieve this buffer’s byte order. The byte order is used when reading or writing multibyte values, and when creating buffers that are views of this byte buffer. The order of a newly-created byte buffer is always BIG_ENDIAN.
Syntax:
public final ByteOrder order()
Return Value: This method returns this buffer’s byte order.
Below are the examples to illustrate the order() method:
Examples 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ByteBuffer bb = ByteBuffer.allocate( 12 );
bb.asIntBuffer()
.put( 10 )
.put( 20 )
.put( 30 );
bb.rewind();
System.out.println( "Original ByteBuffer: " );
for ( int i = 1 ; i <= 3 ; i++)
System.out.print(bb.getInt() + " " );
bb.rewind();
ByteOrder value = bb.order();
System.out.println( "\n\nByte Value: " + value);
}
}
|
Output:
Original ByteBuffer:
10 20 30
Byte Value: BIG_ENDIAN
Examples 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ByteBuffer bb = ByteBuffer.allocate( 12 );
ByteOrder value = bb.order();
System.out.println( "Byte Value: " + value);
}
}
|
Output:
Byte Value: BIG_ENDIAN
order(ByteOrder bo)
The order(ByteOrder bo) method of ByteBuffer is used to modifie this buffer’s byte order.
Syntax:
public final ByteBuffer order(ByteOrder bo)
Parameters: This method takes the new byte order, either BIG_ENDIAN or LITTLE_ENDIAN as a parameter.
Return Value: This method returns This buffer.
Below are the examples to illustrate the order(ByteOrder bo) method:
Examples 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ByteBuffer bb = ByteBuffer.allocate( 12 );
ByteOrder oldbyteorder = bb.order();
System.out.println( "Old Byte Order: " + oldbyteorder);
ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder());
ByteOrder newbyteorder = bb1.order();
System.out.println( "New Byte Order: " + newbyteorder);
}
}
|
Output:
Old Byte Order: BIG_ENDIAN
New Byte Order: LITTLE_ENDIAN
Examples 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ByteBuffer bb = ByteBuffer.allocate( 12 );
bb.asIntBuffer()
.put( 10 )
.put( 20 )
.put( 30 );
bb.rewind();
System.out.println( "Original ByteBuffer: " );
for ( int i = 1 ; i <= 3 ; i++)
System.out.print(bb.getInt() + " " );
bb.rewind();
ByteOrder oldbyteorder = bb.order();
System.out.println( "Old Byte Order: " + oldbyteorder);
ByteBuffer bb1 = bb.order(ByteOrder.nativeOrder());
ByteOrder newbyteorder = bb1.order();
System.out.println( "New Byte Order: " + newbyteorder);
}
}
|
Output:
Original ByteBuffer:
10 20 30 Old Byte Order: BIG_ENDIAN
New Byte Order: LITTLE_ENDIAN
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...