Search code examples
javascripttyped-arrays

Most efficent way to convert a non-typed array of 32-bit integers to a UInt8Array?


I need to take a standard javascript array populated with valid 32-bit signed intergers and convert it to a UInt8Array. For example, consider the following standard javascript array:

[255, 3498766, -99]

I want the resulting UInt8Array to contain the signed 32-bit representation of these numbers:

255     = [0x00, 0x00, 0x00, 0xFF]
3498766 = [0x00, 0x35, 0x63, 0x0E]
-99     = [0xFF, 0xFF, 0xFF, 0x9D]

So, given the an input of [255, 3498766, -99], the result would be:

[0x00, 0x00, 0x00, 0xFF, 0x00, 0x35, 0x63, 0x0E, 0xFF, 0xFF, 0xFF, 0x9D]

I can think of naive ways to accomplish this, but I'm looking for as direct a conversion as possible.


Solution

  • a = [255, 3498766, -99]
    b = new Uint8Array(Int32Array.from(a).buffer)
    console.log(b)

    The result will be in the platform byte order, i.e. LE on most today's processors. If you really want big-endian as in your example, you'll need some additional fiddling with DataView.getInt32 (see here for details).