How can I test whether a number is a power of 2?

(n & (n - 1)) == 0 is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly. has a large collection of clever bit-twiddling algorithms, including this one.

Leave a Comment