Convert FloatBuffer[] to byte[]

1.6k Views Asked by At

I've been searching for a way to convert a FloatBuffer array to a byte array. I have found a way to convert a FloatBuffer object to byte[]: convert from floatbuffer to byte[]

But after searching the Internet for several hours I haven't been able to find something equivalent to convert from FloatBuffer[].

And to do the inverse, to convert from byte[] to FloatBuffer[], I've only found this:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(floatBufferObject);
byte [] descriptorsBytes = bos.toByteArray();

But it seems a little strange there is not a simpler way to do this. Maybe I'm missing something very obvious, maybe I should convert the FloatBuffer array to other type that is simpler to convert to a byte array?

3

There are 3 best solutions below

2
Perception On BEST ANSWER

You already had the answer on how to convert one FloatBuffer into a byte array, so simply extend that to convert an array of them:

final FloatBuffer[] floatBuffers = new FloatBuffer[] {...};
final ByteBuffer byteBuffer = ByteBuffer.allocate(sumOfFloatBufferCapacities) * 4);
final FloatBuffer floatBufView = byteBuffer.asFloatBuffer();
for (final FloatBuffer fBuf : floatBuffers) {
    floatBufView.put(fBuf);
}
byte[] data = byteBuffer.array();

The above is pseudocode, you can adapt it to your needs.

5
Louis Wasserman On

Do you want one FloatBuffer, or multiple?

To convert from a FloatBuffer to a byte[], you could do something like

 FloatBuffer input;
 byte[] output = new byte[input.capacity() * 4];
 ByteBuffer.wrap(output).asFloatBuffer().put(input);

The other direction would just be

 ByteBuffer.wrap(byteArray).asFloatBuffer()
0
Evgeniy Dorofeev On

Convert FloatBuffer[] to byte[]:

    FloatBuffer[] buffers = ...
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (FloatBuffer fb : buffers) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(fb.capacity() * 4);
        byteBuffer.asFloatBuffer().put(fb);
        bos.write(byteBuffer.array());
    }
    byte[] ba = bos.toByteArray();