Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...