Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some great ways to take advantage of bitwise operators?

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?

like image 962
Tower Avatar asked Apr 04 '11 18:04

Tower


2 Answers

Constant time 2-exponentiation:

x = 1 << n; // x = pow(2, n)
like image 171
coldfix Avatar answered Oct 07 '22 21:10

coldfix


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.

like image 38
svenningsson Avatar answered Oct 07 '22 21:10

svenningsson