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

I would like to read a binary file with several 32 bit float values ​​at byte offset 31.

Unfortunately, new Float32Array(buffer, 31, 6); does not work. An offset of 32 instead of 31 works, but I need 31.

According to this page, the offset should be a multiple of the size of the element, in this case 4.

I'm interested in the reason for this behavior. Why does it matter where the show starts from?

The best workaround I have found so far has not yet turned into gecko, so I cannot use it.

Do I need to cut and copy byte values ​​to a new array to get my float values?

+11
source share
3 answers

I'm interested in the reason for this behavior. Why does it matter where the show starts from?

Some architectures do not allow unrelated word accesses, and architectures that allow this, for example, on x86, have performance penalties (although some commands must be aligned).

Do I really need to cut and copy byte values ​​to a new array to get my float values?

Yes, like Marcus’s example, you have to create a new ArrayBuffer with a UInt8Array and a Float32Array for read_buffer (copy from UInt8Array and interpret from the Float32Array ), Then you can read your data using UInt8Array , copy it to the read_buffer , and then interpret using Float32Array . This is a pretty seamless process.

+9
source

DataView.getFloat32 () would be the best way to do this. The DataView is designed for packed data and allows smooth access to data in ArrayBuffer, so you can pass with odd offsets, such as 31.

+5
source

You can use slice to get a new ArrayBuffer whose contents are a copy of this ArrayBuffer byte from the beginning, including to the end

 const buffer = new ArrayBuffer(250); const list = buffer.slice(10); // index [11,250] const nums = new Int32Array(list, 0, 60); 
-one
source

All Articles