[C++] Fast Power of 2 Test

Started by
21 comments, last by DukeAtreides076 17 years, 8 months ago
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?
Advertisement
I found this method here

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

!(a & (--a)) && a;
Thanks, I thought there was a neat little bit manipulation trick to do it. Easier than I thought though.
Quote:Original post by Anonymous Poster
int a;

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

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

Nicksterdomus's method is fine though.
bool is_pow2(const int x) { return ((x & -x) == x); }
Read here:
http://graphics.stanford.edu/~seander/bithacks.html
Quote:Original post by Null and Void
Quote:Original post by Anonymous Poster
int 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
answer = a3 && a1
Quote:Original post by Anonymous Poster
int a;

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


a &(a-1) == 0

(1000 & 0111)==0000

http://www.8ung.at/basiror/theironcross.html
!(a & (--a)) && a;

Quote:Original post by Cocalus
I 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.

This topic is closed to new replies.

Advertisement