Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the bitwise code "$n & ($n - 1)" do?

What does this code mean and what are other ways accomplish the same without using bit shifting?

if ($n & ($n - 1))
like image 205
Alix Axel Avatar asked Oct 11 '09 19:10

Alix Axel


1 Answers

That formula checks to see whether a number is a power of 2 (if your condition as written is true, then the number is not a power of two).

Stated another way, your test checks to see whether there is more than one "1" bit set in the binary representation of $n. If there is zero or only one bit set, then your test will be false.

It is by far the most efficient way to determine that property.

like image 147
Greg Hewgill Avatar answered Sep 20 '22 18:09

Greg Hewgill