Why is creating a Float32Array with an offset that isn't a multiple of the element size not allowed?

后端 未结 3 1728
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 22:35

I\'d like to read a binary file with a few 32 bit float values at byte offset 31.

Unfortunately, new Float32Array(buffer, 31, 6); does not work. An offs

相关标签:
3条回答
  • 2020-12-15 22:58

    I'm interested in the reason behind this behaviour. Why does it matter where the view starts?

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

    Do I really have to cut and copy the byte values into a new array to get my float values?

    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.

    0 讨论(0)
  • 2020-12-15 22:58

    You can use slice to get a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin, inclusive, up to end

    const buffer = new ArrayBuffer(250);
    const list = buffer.slice(10); // index [11,250]
    const nums = new Int32Array(list, 0, 60);
    
    0 讨论(0)
  • 2020-12-15 23:15

    DataView.getFloat32() would be the best way to do this. DataView is designed for packed data and allows unaligned access to the data in an ArrayBuffer so you can pass in odd offsets like 31.

    0 讨论(0)
提交回复
热议问题