Monday, September 21, 2020

Bit-Twiddling Hacks

Sean Eron Anderson has collected a great bunch of bit-twiddling hacks at his website. Even if you may never have a need for operating at this level, it's a good mental exercise to to solve these kinds of puzzles.

For example, a C macro to swap two values without use of a third variable and by only using addition and subtraction:

1
2
#define SWAP(a, b) ((&(a) == &(b)) || \
                    (((a) -= (b)), ((b) += (a)), ((a) = (b) - (a))))

If you really want to jump head-first into the deep end, check out the book Hacker's Delight by Henry S. Warren.

No comments:

Post a Comment