Java I/O How to - Convert ByteBuffer to an IntBuffer








Question

We would like to know how to convert ByteBuffer to an IntBuffer.

Answer

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
/*from  www. ja v a  2 s  .  com*/
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();
    IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
    System.out.println("Int Buffer");
    while (ib.hasRemaining())
      System.out.println(ib.position() + " -> " + ib.get());

  }
}

The code above generates the following result.