# [C++] Fast Power of 2 Test

This topic is 4469 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I need a fast method that will test if a number is a power of 2. So far the fastest method I can think of would be using the std::bitset<> templated container class like this:
bool IsPower2(int number)
{
std::bitset<32> bit_set(number);

return (bit_set.count()<2);
}


Is this method effecient or is there a faster way?

##### Share on other sites
I found this method here

bool IsPower2(int x){	return ( (x > 0) && ((x & (x - 1)) == 0) );}

##### Share on other sites
int a;

!(a & (--a)) && a;

##### Share on other sites
Thanks, I thought there was a neat little bit manipulation trick to do it. Easier than I thought though.

##### Share on other sites
Quote:
 Original post by Anonymous Posterint a;!(a & (--a)) && a;

Do not do it like this, it enters into undefined evaluation order territory.

Nicksterdomus's method is fine though.

##### Share on other sites
bool is_pow2(const int x) { return ((x & -x) == x); }

##### Share on other sites
Quote:
Original post by Null and Void
Quote:
 Original post by Anonymous Posterint a;!(a & (--a)) && a;

Do not do it like this, it enters into undefined evaluation order territory.

Nicksterdomus's method is fine though.

While it should be
!(a & (a-1)) && a
(since the AP's doesn't work)

I don't see the undefined evaulation order.
I looks like it's properly defined as
a1=a-1
a2=a1&a1 //Why the AP's version doesn't work
a3=!a2

##### Share on other sites
Quote:
 Original post by Anonymous Posterint a;!(a & (--a)) && a;

a &(a-1) == 0

(1000 & 0111)==0000

##### Share on other sites
!(a & (--a)) && a;

Quote:
 Original post by CocalusI don't see the undefined evaulation order.

Consider a == 2. The two possible results are:

!(2 & 1) && 1 -> 1

!(1 & 1) && 1 -> 0

Depending on whether (--a) or (a) is evaluated first in the leftmost expression.

1. 1
Rutin
44
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632984
• Total Posts
3009713
• ### Who's Online (See full list)

There are no registered users currently online

×