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
ora + (b << 8)
depending on what you want to do. – Loïc Faure-Lacroix Commented Jun 2, 2020 at 20:20
3 Answers
Reset to default 3You 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
版权声明:本文标题:javascript - convert Uint8Array into Uint16Array in NodeJs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744542130a2611676.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论