Source: Hacker's Delight
http://www.informit.com/articles/article.aspx?p=1959565
x & (x – 1)
To determine if an unsigned integer is a power of 2 or is 0, apply the formula followed by a 0-test on the result.
x & (x + 1)
This can be used to determine if an unsigned integer is of the form 2n– 1, 0, or all 1’s: apply the formula followed by a 0-test on the result.
x | (x + 1)
Use the following formula to turn on the rightmost 0-bit in a word, producing all 1’s if none (e.g., 10100111 ⇒ 10101111):
The Aggregate Magic Algorithms, 26 bit twiddling algorithms from Hank Dietz and others
Bit Twiddling Hacks, by Sean Anderson
http://www.informit.com/articles/article.aspx?p=1959565
x & (x – 1)
To determine if an unsigned integer is a power of 2 or is 0, apply the formula followed by a 0-test on the result.
x & (x + 1)
This can be used to determine if an unsigned integer is of the form 2n– 1, 0, or all 1’s: apply the formula followed by a 0-test on the result.
x | (x + 1)
Use the following formula to turn on the rightmost 0-bit in a word, producing all 1’s if none (e.g., 10100111 ⇒ 10101111):
The Aggregate Magic Algorithms, 26 bit twiddling algorithms from Hank Dietz and others
Bit Twiddling Hacks, by Sean Anderson