Reputation: 1331
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.
Upvotes: 4
Views: 5529
Reputation: 298
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.
Upvotes: 4
Reputation: 1331
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);
Upvotes: 4