2

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?

Yukulélé
  • 15,644
  • 10
  • 70
  • 94

1 Answers1

6

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 !

doom
  • 3,276
  • 4
  • 30
  • 41
  • This was super helpful. Thanks! However what happens when you get a byte offset error: `start offset of Uint16Array should be a multiple of 2`. My buffer has a buffer.byteOffset of 7 – Mauvis Ledford Aug 31 '21 at 10:02