gpt4 book ai didi

java - 将 FloatBuffer 转换为 ByteBuffer

转载 作者:搜寻专家 更新时间:2023-11-01 00:56:17 26 4
gpt4 key购买 nike

ByteBuffer 提供了asFloatBuffer() 函数。但是,没有等效的 FloatBuffer.asByteBuffer()

我正在尝试:

float[] array = ...
try( ByteChannel channel = Files.newByteChannel( path, WRITE, CREATE, TRUNCATE_EXISTING ) ) {
channel.write (FloatBuffer.wrap (array) .asByteBuffer());
}

有没有一种方法可以有效地做到这一点,或者我必须求助于分配一个ByteBuffer,如下所示:

ByteBuffer buffer = ByteBuffer.allocate( array.length * 4 );
buffer .asFloatBuffer() .put (array);
channel.write (buffer);

最佳答案

对于 HeapFloatBuffer,即由 FloatBuffer.allocateFloatBuffer.wrap 创建的,没有简单的解决方案。需要编写扩展 ByteBuffer 的自定义类。

对于 HotSpot 8 中的直接缓冲区,这将适用于简单的情况:

FloatBuffer floatBuffer = ByteBuffer.allocateDirect (...).asFloatBuffer();
ByteBuffer byteBuffer = (ByteBuffer) ((sun.nio.ch.DirectBuffer)floatBuffer).attachment();

对于其他情况,请使用以下内容。请注意,此类在包 java.nio 中声明。这也可能只适用于 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());
}

}

关于java - 将 FloatBuffer 转换为 ByteBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com