Java ByteBuffer store float list

Description

Java ByteBuffer store float list



import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        List<Float> arr = java.util.Arrays.asList(4F, 5F,6F,7F);
        System.out.println(list2ByteBuffer(arr));
    }//from  w w w. java 2s  .c om

    public static ByteBuffer list2ByteBuffer(List<Float> arr) {

        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.size() * 4);
        ibb.order(ByteOrder.nativeOrder());
        FloatBuffer fbb = ibb.asFloatBuffer();
        for (float f : arr) {
            fbb.put(f);
        }
        ibb.position(0);
        return ibb;
    }
}



PreviousNext

Related