Mark
Mark

Reputation: 5038

Convert byte array to integer array on the fly

from a webserver I receive a large byte array that is composed of N integers (signed 16 bit, little endian) and I want to build an array of integers in javascript.

Of course I could just iterate over the incoming array and push in each couple of bytes. There's no problem doing this.

I'm wondering if there is a more convenient way to fill the array. For example, in C, I may set an integer pointer to the first byte and then access to all the others. Or better I can malloc and memcpy the buffer area to a reserved space. In both cases I don't have to iterate the source array.

Upvotes: 1

Views: 2694

Answers (2)

ArjayDee
ArjayDee

Reputation: 11

This will convert two bytes (8 bits each) into an Integer

function Two8bitBytestoOneInteger(byteHighBits,byteLowBits){
   return  ( byteHighBits.charCodeAt(0) << 8 ) | ( byteLowBits.charCodeAt(0) & 0xFF ) ;
}

Hint: if you try to print bytes (i.e. console.log(byteHighBits)) you get an error NaN (not a number) so to see the byte integer value do this ( console.log(byteHighBits.charCodeAt(0) )

Hope this helps!

Upvotes: 1

int3
int3

Reputation: 13201

In newer browsers that support Typed Arrays, you can make an XHR request with the responseType request parameter set to "arraybuffer". The response will then be an ArrayBuffer object, which you can pass to a Int32Array constructor.

Upvotes: 1

Related Questions