Java Reference
In-Depth Information
Listing 9-11 demonstrates 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. The program stores a short value of 300 in two bytes of a byte buffer.
It displays the values stored in the first and the second bytes using both big endian and little endian byte orders.
The output shows the values of bytes in decimal as 1 and 44 , whose binary equivalents are 00000001 and 00101100 ,
respectively.
Listing 9-11. Setting the Byte Order of a Byte Buffer
// ByteBufferOrder.java
package com.jdojo.nio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteBufferOrder {
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();
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();
}
}
Default Byte Order: BIG_ENDIAN
Byte Order: BIG_ENDIAN
1 44
Byte Order: LITTLE_ENDIAN
44 1
 
Search WWH ::




Custom Search