Home Tutorial Java Corejava Nio Order bytes from most significant to least significant.

 
 

Share on Google+Share on Google+
Order bytes from most significant to least significant.
Posted on: July 24, 2010 at 12:00 AM
Advertisement
In this tutorial you will learn about how to order bytes from most significant to least significant.

Order bytes from most significant to least significant.

In this tutorial we will discuss on how to use the ByteOrder class for ordering bytes from most significant to a least significant.

Code:

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

public class ByOrderDemo {

  public static void main(String[] args) {
    ByteBuffer byteBuf = ByteBuffer.wrap(new byte[6]);
    byteBuf.asCharBuffer().put("abc");
    System.out.println(toString(byteBuf.array()));
    byteBuf.rewind();

    byteBuf.order(ByteOrder.BIG_ENDIAN);
    byteBuf.asCharBuffer().put("abc");
    System.out.println(toString(byteBuf.array()));
    byteBuf.rewind();

   }

  static String toString(byte[] a) {
    StringBuffer strbuf = new StringBuffer();
    for (int i = 0; i < a.length; i++) {
      strbuf.append(a[i]);
      if (i < a.length - 1)
        strbuf.append(", ");
    }
    return strbuf.toString();
  }
}

Output:

  0, 97, 0, 98, 0, 99
  0, 97, 0, 98, 0, 99

Download this code

Advertisement

Related Tags for Order bytes from most significant to least significant.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 24, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com