The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Byte Buffers  [8 examples]

e165. Setting the Byte Ordering for a ByteBuffer

By default, the byte ordering for a ByteBuffer is ByteOrder.BIG_ENDIAN. This means that if you put a multibyte value into the buffer, the most significant byte is written out first. With LITTLE_ENDIAN, the least significant byte is written out first.
    // Obtain a ByteBuffer; see also e158 Creating a ByteBuffer
    ByteBuffer buf = ByteBuffer.allocate(10);
    
    // Get default byte ordering
    ByteOrder order = buf.order(); // ByteOrder.BIG_ENDIAN
    
    // Put a multibyte value
    buf.putShort(0, (short)123);
    buf.get(0); // 0
    buf.get(1); // 123
    
    // Set to little endian
    buf.order(ByteOrder.LITTLE_ENDIAN);
    
    // Put a multibyte value
    buf.putShort(0, (short)123);
    buf.get(0); // 123
    buf.get(1); // 0

 Related Examples
e158. Creating a ByteBuffer
e159. Getting Bytes from a ByteBuffer
e160. Putting Bytes into a ByteBuffer
e161. Converting Between a ByteBuffer an a Byte Array
e162. Getting and Setting Non-Byte Java Types in a ByteBuffer
e163. Creating a Non-Byte Java Type Buffer on a ByteBuffer
e164. Using a ByteBuffer to Store Strings

See also: File Locking    Files    Sockets    Streams   


© 2002 Addison-Wesley.