Search code examples
javaarraysbytefloatbuffer

Convert FloatBuffer[] to byte[]


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?


Solution

  • 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.