How Fast is Bit Packing?
lemire.me
lemire.me
But what is shown implemented here is more like a compression / decompression routine, because it's predicated on the idea you want to read / write long strings of numbers. If that's the case, it's probably better to use a cheap and fast stream compression algorithm - you'll lose some speed, but likely gain significant space (depending on data of course).
Many of those encodings and packings, particularly for the fixed-size messages, used structure bitfield magic. We has a few variable-sized messages too, though, where I had to do things like what the OP did.
I believe he wrote the rest of the program as a benchmark for his "chunk oriented" routines using large amounts of data. It doesn't make the pack and unpack routines any less suited to processing small amounts of data.
With a little work, you could use those routines to allow random access to a large packed array with a small buffer -- in the simplest implementation, calculate if the integer you're trying to address is in the buffer, if not, unpack the correct chunk and overwrite the buffer with it.
My point is rather that if you are in a position to bulk read / write, there is probably a better option.
You're right that the benchmark is biased due to cache effects/etc from processing in a large stream, however. A more honest (and useful) benchmark would be to test the performance of packed and unpacked integers under a random access pattern.
If your input is randomly distributed integers in the interval [0, 2^n), a bit-packed coding is the most efficient possible.