array to Byte Buffer - Java java.nio

Java examples for java.nio:ByteBuffer Array

Description

array to Byte Buffer

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        float[] arr = new float[] { 34.45f, 35.45f, 36.67f, 37.78f,
                37.0000f, 37.1234f, 67.2344f, 68.34534f, 69.87700f };
        System.out.println(arr2ByteBuffer(arr));
    }/*from  w ww. j  a  va 2  s . com*/

    public static ByteBuffer arr2ByteBuffer(float[] arr) {

        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.length * 4);
        ibb.order(ByteOrder.nativeOrder());
        FloatBuffer fbb = ibb.asFloatBuffer();
        fbb.put(arr);

        ibb.position(0);
        return ibb;
    }

    public static ByteBuffer arr2ByteBuffer(byte[] arr) {

        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.length);
        ibb.order(ByteOrder.nativeOrder());
        ibb.put(arr);

        ibb.position(0);
        return ibb;
    }
}

Related Tutorials