Fabian
Fabian

Reputation: 130

How can I convert a Uint8Array with offset into an Int32Array?

I have a Uint8Array with an offset that I receive from another function. This contains the data I need, but there is a bit of other stuff at the start of the buffer backing this typed array.

The actual data are 32bit integers, and I'd like to have that data in an Int32Array. But converting this doesn't seem to be straightforward, I'm currently doing it manually the following way:

var outputBuffer = new ArrayBuffer(data.length);
  var inputByteArray = new Uint8Array(outputBuffer);
  for (var i=0; i < data.length; ++i) {
    inputByteArray[i] = data[i]
  }
  var outputInt32Array= new Int32Array(outputBuffer);

The straightforward way of just creating a new Int32Array and passing the source Uint8Array doesn't work:

var outputInt32Array = new Int32Array(data) // data is the Uint8Array with offset

This results in a typed array that still behaves like a Uint8Array and hands out individual bytes, not 32bit integers.

Trying it by passing in the offset also doesn't work, I get the error "RangeError: start offset of Int32Array should be a multiple of 4":

var outputInt32Array = new Int32Array(data.buffer, data.byteOffset, length)

Is manually copying each byte the only way to get an Int32Array out of an Int8Array with an offset?

Upvotes: 0

Views: 4844

Answers (1)

Bergi
Bergi

Reputation: 664579

No, you don't need to manually copy the bytes from one to the other array. Using new Int32Array(data.buffer, …) is the best approach, but if you have a weird offset you will need to use a second buffer that is properly aligned. Still, you don't have to copy it manually, you can just use the slice method:

var outputInt32Array = new Int32Array(data.buffer.slice(data.byteOffset), 0, length);

If you need to access Int32s on the same buffer as data, you can also use a DataView.

Upvotes: 4

Related Questions