我想将buffer转换为Uint16Array
我尝试过:
const buffer = Buffer.from([0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34])
const arr = new Uint16Array(buffer)
console.log(arr)
我希望[0x0000, 0x0002, 0x0100, 0x1234]
但是我得到[0x00, 0x01, 0x00, 0x02, 0x01, 0x00, 0x12, 0x34]
如何将缓冲区转换为16位数组?
答案 0 :(得分:2)
您应该考虑byteOffset缓冲区属性,因为
在Buffer.from(ArrayBuffer,byteOffset, 长度),或者 有时分配的缓冲区小于 Buffer.poolSize ,缓冲区不是从零偏移开始 底层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 ]
相同!