How would I store multiple numbers in a UInt16Array or UInt32Array?

31 Views Asked by At

If I have one small number, that can be from 0-8, and another larger number that can be from 0-50, how would I store both of these numbers in one index of a UInt16Array or UInt32Array?

I want to be able to access both of these values and then set them again.

1

There are 1 best solutions below

3
bogdanoff On

As Jaromanda said, you have to do bitwise operations. Here I am using 16bit to store final value, leftmost bits used for storing 0-50 and rightmost bits used for 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))