convert nodejs buffer to Uint16Array

Issue

I would like to convert a buffer to Uint16Array

I tried:

const buffer = Buffer.from([0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34])
const arr = new Uint16Array(buffer)
console.log(arr)

I expect [0x0001, 0x0002, 0x0100, 0x1234]

but I get [0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34]

how can I convert buffer to 16 bits array?

Solution

You should take in account byteOffset buffer property because

When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset,
length), or sometimes when allocating a Buffer smaller than
Buffer.poolSize
, the buffer does not start from a zero offset on the
underlying ArrayBuffer

You should also take care of endianness

let buffer = Buffer.from([0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34])
buffer.swap16()   // change endianness
let arr = new Uint16Array(buffer.buffer,buffer.byteOffset,buffer.length/2)
console.log(arr)
console.log([0x0001, 0x0002, 0x0100, 0x1234])

output:

> console.log(arr)
Uint16Array(4) [ 1, 2, 256, 4660 ]
> console.log([0x0001, 0x0002, 0x0100, 0x1234])
[ 1, 2, 256, 4660 ]

Same !

Answered By – doom

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.