Search code examples
androidfloatbuffer

Converting byte[] to float[]


I'm trying to convert a float[] to a byte[] in Android. I've looked at other questions and answers on stackoverflow but none of them helped so I decided to implement my own solution. The way I have tried is:

byte[] data = some data;
ByteBuffer buffer = ByteBuffer.allocate(data.length);
buffer.put(data);
FloatBuffer fBuffer = buffer.asFloatBuffer();
float[] dataConverted = fBuffer.array();

However, the exception:

java.lang.UnsupportedOperationException
    at java.nio.ByteBufferAsFloatBuffer.protectedArray(ByteBufferAsFloatBuffer.java:128)
    at java.nio.FloatBuffer.array(FloatBuffer.java:101)

From the line:

    float[] dataConverted = fBuffer.array();

Keeps being thrown, and I'm not sure why. Could someone help explain why this exception is being thrown; it would be of great help?


Solution

  • The FloatBuffer allocated does not have a backing array to return; please refer to FloatBuffer.hasArray(). To achieve the effect that you would like, try copying the FloatBuffer to a float array via FloatBuffer.get(float[])

    Sample code:

    final byte[] data = new byte[] {
            64, 73, 15, -48, 127, 127, -1, -1, 0, 0, 0, 1, 0, 0, 0, 0
    };
    
    final FloatBuffer fb = ByteBuffer.wrap(data).asFloatBuffer();
    final float[] dst = new float[fb.capacity()];
    fb.get(dst); // Copy the contents of the FloatBuffer into dst
    
    for (int i = 0; i < dst.length; i++) {
        System.out.print(dst[i]);
        if (i == dst.length - 1) {
            System.out.println();
        } else {
            System.out.print(", ");
        }
    }
    

    Output:

    3.14159, 3.4028235E38, 1.4E-45, 0.0