如何在 UInt16Array 或 UInt32Array 中存储多个数字?

问题描述 投票:0回答:1

如果我有一个小数字(可以是 0-8)和另一个较大的数字(可以是 0-50),我如何将这两个数字存储在 UInt16Array 或 UInt32Array 的一个索引中?

我希望能够访问这两个值,然后再次设置它们。

javascript unsigned-integer
1个回答
0
投票

正如 Jaromanda 所说,你必须进行按位运算。这里我使用16bit来存储最终值, 最左边的位用于存储 0-50,最右边的位用于存储 0-8。

const result = new Uint16Array([0])

const H = 42
const L = 5

console.log('H: ', H, H.toString(2))
console.log('L: ', L, L.toString(2))

console.log('--------------------')
console.log('result[0] before: ', result[0], result[0].toString(2))
result[0] = H << 8
result[0] = result[0] | L
console.log('result[0] after: ', result[0], result[0].toString(2))
console.log('--------------------')

const dL = result[0] & 0x00ff
const dH = (result[0] & 0xff00) >> 8

console.log('\ndecoded H: ', dH, dH.toString(2))
console.log('decoded L: ', dL, dL.toString(2))

© www.soinside.com 2019 - 2024. All rights reserved.