I have an array:
[43, 44, 45, 46, 47, 2]
And I need to convert it to one 32 bit unsigned integer. So the first 5 values each use 6 bits and the last value uses 2 bits.
On C this code looks like:
varToPack = (array[0] &0x3F) +
( (array[1]<<6) &0x3F) +
( (array[2]<<12) &0x3F) +
( (array[3]<<18) &0x3F) +
( (array[4]<<24) &0x3F) +
( (array[5]<<30) &3)
I want to do the same on JS, I did and it works:
let varToPack = arr[0]+
(arr[1]<<6)+
(arr[2]<<12)+
(arr[3]<<18)+
(arr[4]<<24)+
(arr[5]<<30);
But only when the last value in array[5] will be 0
or 1
. After I set last value to 2 I get negative number. So according to this answer:
Bitwise operations on 32-bit unsigned ints?
I did the following modification:
let varToPack = arr[0]+
(arr[1]<<6)+
(arr[2]<<12)+
(arr[3]<<18)+
(arr[4]<<24)+
((arr[5]<<30)>>>0);
This works, but in sum it returns value gather then 2147483648, because I didn't use &0x3F
that won’t let the number be greater than 6bits.
But when I do:
let varToPack = (arr[0]&0x3F)+
((arr[1]<<6)&0x3F)+
((arr[2]<<12)&0x3F)+
((arr[3]<<18)&0x3F)+
((arr[4]<<24)&0x3F)+
(((arr[5]<<30)>>>0)&3);
It returns 0. What am I doing wrong ?