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?
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:
Output: