问题描述
我想读取一个二进制文件,在字节偏移31处有几个32位浮点值。
I'd like to read a binary file with a few 32 bit float values at byte offset 31.
不幸的是, new Float32Array(缓冲区,31,6);
不起作用。偏移量为32而不是31,但我需要31。
Unfortunately, new Float32Array(buffer, 31, 6);
does not work. An offset of 32 instead of 31 works but I need 31.
根据,偏移量必须是元素大小的倍数,在这种情况下为4。
According to this page, offset has to be a multiple of the element size, 4 in this case.
我对这种行为背后的原因感兴趣。为什么视图的开始位置很重要?
I'm interested in the reason behind this behaviour. Why does it matter where the view starts?
还没有成为壁虎,所以我不能使用它。
The best workaround I found thus far has not made it into gecko yet so I can't use it.
我真的必须剪切并将字节值复制到一个获取浮动值的新数组?
Do I realy have to cut and copy the byte values into a new array to get my float values?
推荐答案
某些体系结构不允许未对齐的字访问,并且对架构有性能损失允许它如x86(虽然一些指令必须对齐)。
Some architectures do not allow unaligned word accesses, and there are performance penalties on architectures that do allow it such as x86 (though some instructions must be aligned).
是的,就像Markus的例子一样,你应该创建一个新的 ArrayBuffer
带有 UInt8Array
视图和一个 Float32Array
视图,用于 read_buffer
(使用 UInt8Array复制
查看并解释 Float32Array
视图)。然后,您可以使用 UInt8Array
读取数据,将其复制到 read_buffer
视图中,然后使用<$解释C $ C> Float32Array 。这是一个非常无缝的过程。
Yes, just like Markus' example you should create a new ArrayBuffer
with a UInt8Array
view and a Float32Array
view for a read_buffer
(copy with UInt8Array
view and interpret from Float32Array
view). Then you can read from your data with a UInt8Array
, copy that into your read_buffer
view and then interpret using the Float32Array
. It's quite a seamless process.
这篇关于为什么创建一个Float32Array,其偏移量不是不允许的元素大小的倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!