'convert Uint8Array into Uint16Array in NodeJs
I have an Uint8Array that i would like to convert into an Uint16Array so that each consecutive pair of element in the Uint8Array is converted in a Uint16 value. At the end, the uint16Array is thus half the size of the Uint8Array. I thus want to cast the whole array, not each values.
the only solution i found keeps the same lenght and change the underlying type of each element of the array. So it does not 'cast' the array but each element of the array, which is not what i want.
Solution 1:[1]
If I understood correctly the question, the most native way coming to my mind (which still not is cast but requires a few lines) is converting to a Buffer
, than converting it to a Uint16Array
.
Following snippet seems to achieve the desired result.
const ar8 = new Uint8Array([0, 1, 1, 0, 0, 2, 2, 0]);
const buf = new Buffer(ar8);
const ar16 = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint16Array.BYTES_PER_ELEMENT);
console.log(ar8, buf, ar16);
On my platform conversion is little endian; sorry but I don't know if conversion is little endian on all platforms or little/big endian conversion is platform dependent.
Solution 2:[2]
You can instantiate Uint16Array
from Uint8Array
buffer
value:
const uint8Array = new Uint8Array([1, 164, 5, 57])
const uint16Array = new Uint16Array(uint8Array.buffer)
// Uint16Array(2) [ 41985, 14597 ]
Solution 3:[3]
Your current solution should work fine. The "underlying type" of each element in a Uint8Array
is number
, just like in a Uint16Array
. Therefore, casting the whole array should preserve the types of the values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniele Ricci |
Solution 2 | Metu |
Solution 3 | sugarfi |