1

Is there a good way to combine ByteBuffer & FloatBuffer ? For example I get byte[] data and I need to convert it to float[] data and vice versa :

byte[] to float[] (java.lang.UnsupportedOperationException) :

byte[] bytes = new bytes[N];
ByteBuffer.wrap(bytes).asFloatBuffer().array();

float[] to byte[] (works) :

float[] floats = new float[N];
FloatBuffer floatBuffer = FloatBuffer.wrap(floats);
ByteBuffer byteBuffer = ByteBuffer.allocate(floatBuffer.capacity() * 4);
byteBuffer.asFloatBuffer().put(floats);
byte[] bytes = byteBuffer.array();
xunien
  • 185
  • 1
  • 9

2 Answers2

1

array() is an optional operation for ByteBuffer and FloatBuffer, to be supported only when the backing Buffer is actually implemented on top of an array with the appropriate type.

Instead, use get to read the contents of the buffer into an array, when you don't know how the buffer is actually implemented.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • I think that the better way is to create my own buffer, because I need to put an array et get array not a simple value. – xunien Jul 08 '12 at 19:23
  • To be clear, I'm referring to the `get(byte[])` and `get(float[])` overloads, so you'd still be getting out an array. – Louis Wasserman Jul 08 '12 at 19:42
  • I understand, but my buffer is a byte array, so I can't convert it to a float array – xunien Jul 08 '12 at 20:00
  • That's more or less equivalent, but the code is much less simple that way. I'm still not seeing why you don't just do `FloatBuffer fb = bb.asFloatArray(); float[] farr = new float[fb.remaining()]; fb.get(farr);`. – Louis Wasserman Jul 08 '12 at 21:12
1

To add to Louis's answer, arrays in Java are limited in that they must be an independent region of memory. It is not possible to have an array that is a view of another array, whether to point at some offset in another array or to reinterpret the bytes of another array as a different type.

Buffers (ByteBuffer, FloatBuffer, etc) were created to overcome this limitation. They are equivalent to arrays in that they compile into machine instructions that are as fast as array accesses, despite requiring the programmer to use what appear to be function calls.

For top performance and minimum memory usage, you should use ByteBuffer.wrap(bytes).asFloatBuffer() and then call get() and put().

To get a float array, you must allocate a new array and copy the data into it with ByteBuffer.wrap(bytes).asFloatBuffer().get(myFloatArray).

The array method of a ByteBuffer is not something that anyone should normally use. It will fail unless the Buffer is wrapping an array (instead of pointing to some memory-mapped region like a file or raw non-GC memory) and the array is of the same type as the buffer.

Aleksandr Dubinsky
  • 22,436
  • 15
  • 82
  • 99