node.jsarraybuffertypedarray

In16Array to Buffer to Int16rray


In Node.js, I was trying to cast a buffer which contains Int16Array buffer elements like below. I have a list of numbers like following 255,256,257,258

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

So when I have a buffer like <Buffer ff 00 00 01 01 01 02 01> what should I do to return back to the original array as 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]

Solution

  • Just as the comment says, typed arrays have constructor creating a view of an existing buffer:

    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);


    Ok, sorry, I missed the Node.js part. So, according to Buffer, a Buffer is an Uint8Array for most purposes:

    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);