Skip to content
Advertisement

Bitwise packing/unpacking – generalized solution for arbitrary values

I’m trying to adapt this answer to arbitrary numeric values.

Let’s say we have 3 (unsigned) numbers:

v1, v2, v3

and we know the respective max values they may have:

max1, max2, max3.

max1 * max2 * max3 < 2^32,

so the result (packed value) is to be within 32 bits.

How to pack/unpack them without “magic” hardcoding?

Advertisement

Answer

Here is a slightly different way to do it.

JavaScript

shift values determined based on most significant set bit of maximums.

JavaScript

mask values determined by complementing -1 shifted size bits.

JavaScript

Nothing really new here. Second shift shifts both first and second values.

JavaScript

Now reverse it

JavaScript

Prints

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement