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








Question

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

Answer

import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
/*from   w w  w.  jav  a  2 s .c  om*/
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();
    ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
    System.out.println("Short Buffer");
    while (sb.hasRemaining())
      System.out.println(sb.position() + " -> " + sb.get());

  }
}

The code above generates the following result.