These Bit Twiddling Tricks Will Make Your Coworkers Hate You

These Bit Twiddling Tricks Will Make Your Coworkers Hate You

In the embedded world, twiddling a few bits is expected behavior. Firmware is far enough down the stack that the author may care about the number of bits and bytes used, or needs to work with registers directly to make the machine dance. Usually these operations are confined to the typical shifting and masking but sometimes a problem calls for more exotic solutions. If you need to descend down these dark depths you invariably come across the classic Bit Twiddling Hacks collected by [Sean Eron Anderson]. Here be dragons.


Discussions of bit math are great opportunities to revisit Wikipedia’s superb illustrations

Bit Twiddling Hacks is exactly as described; a page full of snippets and suggestions for how to perform all manner of bit math in convenient or efficient ways. To our surprise upon reading the disclaimer at the top of the page, [Sean] observes that so many people have used the contents of the page that it’s effectively all been thoroughly tested. Considering how esoteric some of the snippets are we’d love to know how the darkest corners found use.


The page contains a variety of nifty tricks. Interview content like counting set bits makes an early appearance.  There’s more esoteric content like this trick for interleaving the bits in two u16’s into a single u32, or rounding up to the next power of two by casting flo ..

Support the originator by clicking the read the rest link below.