簡體   English   中英

將 nodejs 緩沖區轉換為 Uint16Array

[英]convert nodejs buffer to Uint16Array

我想將緩沖區轉換為 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緩沖區屬性,因為

在 Buffer.from(ArrayBuffer, byteOffset, length) 中設置 byteOffset 時,或者有時在分配小於 Buffer.poolSize 的 Buffer 時,緩沖區不會從底層 ArrayBuffer 上的零偏移量開始

您還應該注意字節順序

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 ]

相同的 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM