Extracting bits with a single multiplication

I saw an interesting technique used in an answer to another question, and would like to understand it a little better.

We’re given an unsigned 64-bit integer, and we are interested in the following bits:

1.......2.......3.......4.......5.......6.......7.......8.......

Specifically, we’d like to move them to the top eight positions, like so:

12345678........................................................

We don’t care about the value of the bits indicated by ., and they don’t have to be preserved.

The solution was to mask out the unwanted bits, and multiply the result by 0x2040810204081. This, as it turns out, does the trick.

How general is this method? Can this technique be used to extract any subset of bits? If not, how does one figure out whether or not the method works for a particular set of bits?

Finally, how would one go about finding the (a?) correct multiplier to extract the given bits?

5 Answers
5

Leave a Comment