Java I/O How to - Convert ByteBuffer to a LongBuffer








Question

We would like to know how to convert ByteBuffer to a LongBuffer.

Answer

import java.nio.ByteBuffer;
import java.nio.LongBuffer;
/*from w w  w . ja  v a  2 s.  co  m*/
public class MainClass {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });
    bb.rewind();
    LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
    System.out.println("Long Buffer");
    while (lb.hasRemaining())
      System.out.println(lb.position() + " -> " + lb.get());
  }
}

The code above generates the following result.