3

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.

Peter Prographo
  • 1,141
  • 1
  • 10
  • 27
  • 1
    See also [this question](https://stackoverflow.com/questions/7869752/javascript-typed-arrays-and-endianness) for some interesting food for thought. – Pointy Aug 23 '20 at 17:20

2 Answers2

3

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);
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Peter Prographo
  • 1,141
  • 1
  • 10
  • 27
3

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.

Asraelite
  • 288
  • 4
  • 12