# Check if power of 2 algorithm ???

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi All,

I have a question about a formula I found online at
http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 .

To determine if an integer is a power of 2, the author states that:

f = (v & (v -1)) == 0;

I am very proficient with scripting techniques using PHP so I
understand what we're trying to accomplish here.

However, I can't seem to figure out how to make the example work... :-(

Take, for example, 16.

f = (16 & (16 - 1)) == 0;
f = (16 & (15)) == 0;

The test is always false????????

I think I am not understanding the steps completely...

For reference, in PHP, there is no operator &. The logical AND operator
is &&.

In PHP, the same formula would be written as:

if((v && (v-1)) == 0){
return true;
}

Can anyone explain this to me? I would greatly appreciate any help.

Tim Bellefy

## Re: Check if power of 2 algorithm ???

Emmm, you know you need to prefix variable names with dollar signs,
right?

## Re: Check if power of 2 algorithm ???

Sorry...

if((\$v && (\$v-1)) == 0){
return true;
}

OR

\$r = (\$v && (\$v) == 0 ? true : false);

## Re: Check if power of 2 algorithm ???

Well I fell like a moron...

The & is a bitwise operator and the function works just fine...

I forgot all about those littly guys.

Sorry for my rookie mistake.

## Re: Check if power of 2 algorithm ???

bellefy@gmail.com wrote:

Hehe, and it's even in the url: "bithacks" :-)

Grtz,
--
Rik Wasmus

## Re: Check if power of 2 algorithm ???

bellefy@gmail.com wrote:

Better:

\$r = ((\$v & (\$v-1)) == 0);

NEVER code '?true:false' (or the opposite).

--
Toby A Inkster BSc (Hons) ARCS
Contact Me  ~ http://tobyinkster.co.uk/contact

## Re: Check if power of 2 algorithm ???

Toby Inkster wrote:

This makes 0 a power of two...

Try:
\$r = !(\$v & (\$v-1)) && \$v;

-david-

## Re: Check if power of 2 algorithm ???

Since it also fails for negative numbers, you might as well include that
case:

\$r = !(\$v & (\$v-1)) && (\$v > 0);

- Dana