Today I needed a simple algorithm for checking if a number is a power of 2.
The algorithm needs to be:
ulong
return ((x != 0) && !(x & (x - 1)));
If x
is a power of two, its lone 1 bit is in position n
. This means x – 1
has a 0 in position n
. To see why, recall how a binary subtraction works. When subtracting 1 from x
, the borrow propagates all the way to position n
; bit n
becomes 0 and all lower bits become 1. Now, since x
has no 1 bits in common with x – 1
, x & (x – 1)
is 0, and !(x & (x – 1))
is true.