Bit Twiddling Hacks
The basic bit hack is probably No-Temp Swap:
x = x ^ y;
y = x ^ y;
x = x ^ y;
Today I learned there is also No-Branch Minimum:
r = y ^ ((x ^ y) & -(x < y));
It reminds me of the following hack which I haven’t used for a long time:
r = x & (-x);
A variant of this is to reset the least-significant 1
bit:
x &= x - 1;
But these are all elementary when compared to this:
const uint64_t deBruijn = 0x022fdd63cc95386d;
const unsigned int convert[64] = {
0, 1, 2, 53, 3, 7, 54, 27,
4, 38, 41, 8, 34, 55, 48, 28,
62, 5, 39, 46, 44, 42, 22, 9,
24, 35, 59, 56, 49, 18, 29, 11,
63, 52, 6, 26, 37, 40, 33, 47,
61, 45, 43, 21, 23, 58, 17, 10,
51, 25, 36, 32, 60, 20, 57, 16,
50, 31, 19, 15, 30, 14, 13, 12
};
r = convert[(x*deBruijn) >> 58];
The explanation is here.
-
A great slide by Prof. Charles E. Leiserson.
-
Bit Twiddling Hacks from Sean Eron Anderson at Stanford.
-
A Quora thread.