Search code examples
node.jsbuffer

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>


i look at the nodejs document where i see that and my question is why buf1 is not <Buffer 88 13 a0 0f> ?


Solution

  • It is explained here that Buffer.from behaves as new Uint8Array() which can only contain numbers from 0 to 255 (1 byte) and here is stated that each value is converted and the result array length will be the same (so it can't have 4 elements). When converted, 2 byte value will be trimmed to 1 byte value, ignoring the second byte (88 13 -> 88, a0 0f -> a0).