ByteBuffer
offers asFloatBuffer()
function. However, there is no equivalent FloatBuffer.asByteBuffer()
I am trying to do:
float[] array = ...
try( ByteChannel channel = Files.newByteChannel( path, WRITE, CREATE, TRUNCATE_EXISTING ) ) {
channel.write (FloatBuffer.wrap (array) .asByteBuffer());
}
Is there a way of efficiently doing this, or do I have to resort to allocating a ByteBuffer
as in:
ByteBuffer buffer = ByteBuffer.allocate( array.length * 4 );
buffer .asFloatBuffer() .put (array);
channel.write (buffer);
For a HeapFloatBuffer
, ie created by FloatBuffer.allocate
or FloatBuffer.wrap
, there is no easy solution. A custom class extending ByteBuffer needs to be written.
For direct buffers in HotSpot 8, this will work in the trivial case:
FloatBuffer floatBuffer = ByteBuffer.allocateDirect (...).asFloatBuffer();
ByteBuffer byteBuffer = (ByteBuffer) ((sun.nio.ch.DirectBuffer)floatBuffer).attachment();
For other situations, use the following. Note that this class is declared in package java.nio
. This also probably will only work in HotSpot 8.
package java.nio;
/**
*
* @author Aleksandr Dubinsky
*/
public class BufferUtils {
public static ByteBuffer
asByteBuffer (FloatBuffer floatBuffer) {
if (floatBuffer instanceof DirectFloatBufferU)
{
DirectFloatBufferU buffer = (DirectFloatBufferU) floatBuffer;
return (ByteBuffer) new DirectByteBuffer (buffer.address(), floatBuffer.capacity() * Float.BYTES, buffer)
.position (floatBuffer.position() * Float.BYTES)
.limit (floatBuffer.limit() * Float.BYTES);
}
else if (floatBuffer instanceof DirectFloatBufferS)
{
DirectFloatBufferS buffer = (DirectFloatBufferS) floatBuffer;
return (ByteBuffer) new DirectByteBuffer (buffer.address(), floatBuffer.capacity() * Float.BYTES, buffer)
.position (floatBuffer.position() * Float.BYTES)
.limit (floatBuffer.limit() * Float.BYTES);
}
else if (floatBuffer instanceof ByteBufferAsFloatBufferB)
{
ByteBufferAsFloatBufferB buffer = (ByteBufferAsFloatBufferB)floatBuffer;
return (ByteBuffer) ((ByteBuffer) buffer.bb
.duplicate()
.position (buffer.offset)
.limit (buffer.offset + buffer.capacity() * Float.BYTES))
.slice()
.position (buffer.position() * Float.SIZE)
.limit (buffer.limit() * Float.BYTES);
}
else if (floatBuffer instanceof ByteBufferAsFloatBufferL)
{
ByteBufferAsFloatBufferL buffer = (ByteBufferAsFloatBufferL)floatBuffer;
return (ByteBuffer) ((ByteBuffer) buffer.bb
.duplicate()
.position (buffer.offset)
.limit (buffer.offset + buffer.capacity() * Float.BYTES))
.slice()
.position (buffer.position() * Float.SIZE)
.limit (buffer.limit() * Float.BYTES);
}
else
throw new IllegalArgumentException ("Unsupported implementing class " + floatBuffer.getClass().getName());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With