node.js 来自 Uint16Array 的缓冲区

node.js Buffer from Uint16Array

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);

// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);


console.log(buf1, buf2 );

// Prints: <Buffer 88 a0>

// Prints: <Buffer 88 13 a0 0f>


我查看了我看到的 nodejs 文档 我的问题是为什么 buf1 不是 ?

解释说 here that Buffer.from behaves as new Uint8Array() which can only contain numbers from 0 to 255 (1 byte) and here 表示每个值都被转换并且结果数组长度将相同(因此它不能有 4 个元素)。转换时,2 字节值将被修剪为 1 字节值,忽略第二个字节(88 13 -> 88a0 0f -> a0)。