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
Add a ment  | 

2 Answers 2

Reset to default 4

Looks 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