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








Question

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

Answer

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
//from  w w  w.  j a va  2  s.c  o 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();
    FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
    System.out.println("Float Buffer");
    while (fb.hasRemaining())
      System.out.println(fb.position() + " -> " + fb.get());

  }
}

The code above generates the following result.