admin管理员组文章数量:1326104
I have a process returning some raw binary data as a Uint8Array, the data represents two unsigned 32bit numbers (Uint32)...
On the browser console:
data: Uint8Array(8) [1, 0, 0, 0, 2, 0, 0, 0]
This represents two unsigned 32 bit numbers (4 bytes each)
How do I convert this into javascript numbers?
I tried Uint32Array.from(x) but that created an array of 8 numbers, which is wrong.
The first 4 bytes -> 1, next 4 bytes -> 2 => array of 2 numbers please.
I have a process returning some raw binary data as a Uint8Array, the data represents two unsigned 32bit numbers (Uint32)...
On the browser console:
data: Uint8Array(8) [1, 0, 0, 0, 2, 0, 0, 0]
This represents two unsigned 32 bit numbers (4 bytes each)
How do I convert this into javascript numbers?
I tried Uint32Array.from(x) but that created an array of 8 numbers, which is wrong.
The first 4 bytes -> 1, next 4 bytes -> 2 => array of 2 numbers please.
Share Improve this question asked Aug 23, 2020 at 17:09 Peter PrographoPeter Prographo 1,3311 gold badge13 silver badges29 bronze badges 1- 1 See also this question for some interesting food for thought. – Pointy Commented Aug 23, 2020 at 17:20
2 Answers
Reset to default 4Looks like this works:
let a = new Uint8Array( [1,0,0,9, 2,0,0,9] );
let b = new Uint32Array( a.buffer );
console.log(b);
let c = new Uint8Array( b.buffer );
console.log(c);
Peter Prographo's solution only works if the TypedArray view spans the entire range of the underlying ArrayBuffer. If the TypedArray is instead created with a byte offset, for example:
let array8 = new Uint8Array(myArrayBuffer, 128, 16);
let array32 = new Uint32Array(array8.buffer);
Then the new Uint32Array will cover the entire buffer, instead of just the range 128..144 as it should.
To handle this, you can do
let array32 = new Uint32Array(array8.buffer, array8.byteOffset, array8.byteLength / 4);
If you are using a different TypedArray than Uint32Array, Replace the 4 with the number of bytes per element of your TypedArray: 2 for Uint16Array, and 8 for BigUint64Array.
本文标签: javascriptUint8Array to Uint32Array (client)Stack Overflow
版权声明:本文标题:javascript - Uint8Array to Uint32Array (client) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742192985a2430554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论