Node: Uint16Array conversion to Buffer doesn't work (truncates data)

Created on 18 Mar 2016  路  2Comments  路  Source: nodejs/node

  • Version: v5.8.0
  • Platform: Linux ape 4.4.5-1-ARCH #1 SMP PREEMPT Thu Mar 10 07:38:19 CET 2016 x86_64 GNU/Linux
  • Subsystem: Node's Buffer implementation (I think)
  • Steps to Reproduce: I opened a node shell and ran these:
> new Buffer(Uint16Array.from([255]))
<Buffer ff>
> new Buffer(Uint16Array.from([65535]))
<Buffer ff>

As far as I understand from node's Buffer documentation, this is not expected behavior, the 8 most significant bits in every element of any Uint16Array are just truncated because every element of Uint16Array is converted to an element of Buffer. But Buffer elements are 1 byte long, while Uint16Array's are 2 bytes long, so every element from the Uint16Array should be two Buffer elements.

Relevant documentation (from node):

const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;

const buf = new Buffer(arr.buffer); // shares the memory with arr;

console.log(buf);
  // Prints: <Buffer 88 13 a0 0f>

Thanks for looking into this issue :+1: I'll try testing on older versions of node to narrow this down if I have time.

buffer

Most helpful comment

> new Buffer(Uint16Array.from([65535]).buffer)
<Buffer ff ff>

What you want to use is the Uint16Array鈥檚 ArrayBuffer, not the array itself (compare the arr.buffer part of the doc excerpt).

All 2 comments

> new Buffer(Uint16Array.from([65535]).buffer)
<Buffer ff ff>

What you want to use is the Uint16Array鈥檚 ArrayBuffer, not the array itself (compare the arr.buffer part of the doc excerpt).

Wow, I just tried that and it worked. My fault! Thanks for the quick answer! I guess I should have RTFM.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fanjunzhi picture fanjunzhi  路  3Comments

Icemic picture Icemic  路  3Comments

filipesilvaa picture filipesilvaa  路  3Comments

cong88 picture cong88  路  3Comments

willnwhite picture willnwhite  路  3Comments