将 nodejs 缓冲区转换为 Uint16Array

convert nodejs buffer to Uint16Array

我想将 buffer 转换为 Uint16Array

我试过了:

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

我希望[0x0001, 0x0002, 0x0100, 0x1234]

但我得到 [0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34]

如何将缓冲区转换为 16 位数组?

您应该考虑 byteOffset 缓冲区 属性 因为

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

你也要照顾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])

输出:

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

一样!