In16Array 到 Buffer 到 Int16rray

In16Array to Buffer to Int16rray

在 Node.js 中,我试图转换一个包含 Int16Array 缓冲区元素的缓冲区,如下所示。 我有一个数字列表,如下所示 255,256,257,258

Int16Array(4) [ 255, 256, 257, 258 ]
<Buffer ff 00 00 01 01 01 02 01>

所以当我有像 <Buffer ff 00 00 01 01 01 02 01> 这样的缓冲区时,我应该怎么做才能 return 回到原始数组 255,256,257,258

var ar = new Int16Array([255, 256, 257, 258])
var buf = Buffer.from(ar.buffer)
console.log('Here we have this', buf)
> <Buffer ff 00 00 01 01 01 02 01>

//And I need to cast back to array as [255,256,257,258]

正如评论所说,类型化数组具有创建现有缓冲区视图的构造函数:

let bytes=Uint8Array.of(0xff,00,00,01,01,01,02,01); // <= from your log
let buf=bytes.buffer;
let shorts=new Int16Array(buf);
for(let x of shorts)
  console.log(x);


好的,抱歉,我错过了 Node.js 部分。因此,根据 BufferBuffer 在大多数情况下是 Uint8Array

var ar = new Int16Array([255, 256, 257, 258]);
var buf = Buffer.from(ar.buffer);
console.log('Here we have this', buf);
var other = new Int16Array(buf.buffer);
for(let x of other)
  console.log(x);