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 offset of 32 instead of 31 works but I need 31.
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?
Normal arrays can be as fast as typed arrays if you do a lot of sequential access. Random access outside the bounds of the array causes the array to grow. Typed arrays are fast for access, but slow to be allocated. If you create temporary arrays frequently, avoid typed arrays.
The Float32Array() typed array constructor creates a new Float32Array object, which is, an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0 .
JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.
The Uint8Array() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
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.
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