Today I needed a simple algorithm for checking if a number is a power of 2.
The algorithm needs to be:
ulong
Some sites that document and explain this and other bit twiddling hacks are:
And the grandaddy of them, the book "Hacker's Delight" by Henry Warren, Jr.:
As Sean Anderson's page explains, the expression ((x & (x - 1)) == 0) incorrectly indicates that 0 is a power of 2. He suggests to use:
(!(x & (x - 1)) && x)
to correct that problem.