convert float array to FloatBuffer - Java java.nio

Java examples for java.nio:FloatBuffer

Description

convert float array to FloatBuffer

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

public class Main {
    public static void main(String[] argv) throws Exception {
        float[] data = new float[] { 34.45f, 35.45f, 36.67f, 37.78f,
                37.0000f, 37.1234f, 67.2344f, 68.34534f, 69.87700f };
        System.out.println(convert(data));
    }//from w w w. j  av a2 s  .  c  o  m

    public static FloatBuffer convert(float[] data) {
        ByteBuffer bb = ByteBuffer.allocateDirect(data.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer floatBuffer = bb.asFloatBuffer();
        floatBuffer.put(data);
        floatBuffer.position(0);
        return floatBuffer;
    }

    public static ShortBuffer convert(short[] data) {
        ByteBuffer bb = ByteBuffer.allocateDirect(data.length * 2);
        bb.order(ByteOrder.nativeOrder());
        ShortBuffer shortBuffer = bb.asShortBuffer();
        shortBuffer.put(data);
        shortBuffer.position(0);
        return shortBuffer;
    }
}

Related Tutorials