I constantly meet people using bitwise operators to do quick, easy and elegant things. I'd like to learn some useful tricks. What are some of the most useful bitwise operator cases?
Constant time 2-exponentiation:
x = 1 << n; // x = pow(2, n)
While I agree with Michael McGowan in general, bit twiddling hacks can be very useful in certain situations, for instance when programming embedded hardware which doesn't have all the usual instructions. I've also had good use for such techniques when encoding programs into theorem provers such as SMT solvers, which didn't support all the operations I wanted to use.
My first stop when looking for a bitwise solution to a problem is the site bit twiddling hacks. It has quite a few code snippets for many of the most common techniques.
Then there's also the book Hacker's Delight covers a few bitwise techniques in depth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With