将NodeJS缓冲区转换为Uint16Array [英] convert nodejs buffer to Uint16Array
本文介绍了将NodeJS缓冲区转换为Uint16Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要将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位数组?
推荐答案
您应该考虑byteOffset缓冲区属性,因为
在Buffer.from(ArrayBuffer,byteOffset, Length),或在分配小于以下值的缓冲区时有时 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 ]
相同!
这篇关于将NodeJS缓冲区转换为Uint16Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文