I have a series of numbers that are between 0 and 1023.
And I wanted to see if I could pack them into a single Uint8Array.
And then read them back to their original values.
But I can’t seem to get the logic right.
function writeInt10(arr, off, a, b, c, d)
{
/*
a 0, 1
b 1, 2, 3
c 3, 4
d 4, 5
*/
arr[off+0] = ((a >> 0) & 0xff);
arr[off+1] = ((a >> 6) & 0xf) | ((b >> 2) & 0xf);
arr[off+2] = ((b >> 4) & 0xf) | ((c >> 4) & 0xf);
arr[off+3] = ((c >> 2) & 0xf) | ((d >> 6) & 0xf);
arr[off+4] = ((d >> 4) & 0xf);
}
function readInt10(arr, off) {
var a = arr[off+0] << 0 | arr[off+1] << 2
var b = arr[off+1] << 6 | arr[off+2] << 4
var c = arr[off+2] << 0 | arr[off+3] << 8
var d = arr[off+3] << 0 | arr[off+4] << 8
return [a, b, c, d];
}
var buf = new Uint8Array(5);
var write = writeInt10(buf, 0, 1023, 100, 512, 768)
var read = readInt10(buf, 0)
console.log(read)
2
Answers
Your
0xf
masks are wrong. You’ll need0x3
,0xc
,0xf
respectively:Also you didn’t apply any bitmasks in
readInt10
, and I think your offsets are wrong (or I didn’t understand your pattern, as you somehow spread b across 3 bytes). Here’s how I’d do it:(I’ve assumed most significant bit first order)
In order to accomplish the task it seems to be a lot simpler to collect all "excess bits" in a single element, although this makes another storage sequence: