admin管理员组

文章数量:1386684

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.

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.

Share Improve this question asked Jun 2, 2020 at 20:09 HattoriHattori 3716 silver badges17 bronze badges 1
  • 1 Is there a particular reason to do that?... If you want to do that you'll have to create a new array with half the length and simply set the values as (a << 8) + b or a + (b << 8) depending on what you want to do. – Loïc Faure-Lacroix Commented Jun 2, 2020 at 20:20
Add a ment  | 

3 Answers 3

Reset to default 3

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 ]

If I understood correctly the question, the most native way ing 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.

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.

本文标签: javascriptconvert Uint8Array into Uint16Array in NodeJsStack Overflow