In Java: convert an array of floats to bytes and vice versa I'm just returning to Java after a multi-decade hiatus -- there are some nice new packages, such as java.nio.
I need to convert an array of floats into bytes and vice versa.  The floatToBytes() function feels okay, but I'm pretty certain that bytesToFloats() could be implemented better.  Thoughts?
(P.S.: ignore the public, protected etc -- this code is wrapped inside a class...)
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

    protected static final int BYTES_PER_FLOAT = Float.SIZE / 8;

    public static byte[] floatsToBytes(float[] floats){
        ByteBuffer buffer = 
                ByteBuffer.allocate(BYTES_PER_FLOAT * floats.length).
                order(ByteOrder.BIG_ENDIAN);
        for (float f : floats) {
            buffer.putFloat(f);
        }
        return buffer.array();
    }
    
    protected static float[] bytesToFloats(byte[] bytes) {
        if (bytes.length % BYTES_PER_FLOAT != 0) {
            throw new RuntimeException(&quot;Illegal length&quot;);
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
        int n_floats = bytes.length / BYTES_PER_FLOAT;
        float[] floats = new float[n_floats];
        for (int i=0; i&lt;n_floats; i++) {
            floats[i] =  buffer.getFloat(i * BYTES_PER_FLOAT);
        }
        return floats;
    }


I also note that there's a FloatBuffer class -- would that be appropriate here?
Welcome again to Code Review, not my field but from a not so clear documentation it seems that you can rewrite your bytesToFloats method using the FloatBuffer class like below, using the asFloatBuffer method from ByteBuffer class:
ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
FloatBuffer fb = buffer.asFloatBuffer();

After you have to back the FloatBuffer buffer allocating a new float array like below:
float[] floats = new float[bytes.length / BYTES_PER_FLOAT];
fb.get(floats);

Then your method can be rewritten like below:
protected static float[] bytesToFloats(byte[] bytes) {

    if (bytes.length % BYTES_PER_FLOAT != 0) {
        throw new RuntimeException(&quot;Illegal length&quot;);
    }
    
    ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
    FloatBuffer fb = buffer.asFloatBuffer();
    float[] floats = new float[bytes.length / BYTES_PER_FLOAT]; 
    
    fb.get(floats);

    return floats;

}

In alternative to the bytes.length / BYTES_PER_FLOAT the fb.limit() method seems returning the same result, moreover it is bound directly to the FloatBuffer fb used.