Lately we needed to put a pair of small integers into a single int variable. (Let us gloss over the intricacies of what an int actually is and just assume it is 32-bit, shall we?) Nothing crazy hard but still, it took some trial and error before we got it right. So, if anybody needs it or is just curious, here’s the code:

The code will test all possible tuples and quit if some unpacking gives an unexpected result.

As further reference, check out the classic page Bit Twiddling Hacks, which contains a lot of efficient algorithms for all kinds of bitwise operations!