How to convert a float into a byte array and vice versa?

Also based on Shazin solution, with additional specification on byte order:

ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(value).array();

or

ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putFloat(value).array();

Use these instead.

public static byte [] long2ByteArray (long value)
{
    return ByteBuffer.allocate(8).putLong(value).array();
}

public static byte [] float2ByteArray (float value)
{  
     return ByteBuffer.allocate(4).putFloat(value).array();
}

Just to add another useful one based on @shazin solution. Convert a float array into a byte array:

public static byte[] FloatArray2ByteArray(float[] values){
    ByteBuffer buffer = ByteBuffer.allocate(4 * values.length);

    for (float value : values){
        buffer.putFloat(value);
    }

    return buffer.array();
}

Tags:

Java