bool IsPower2(int number)
{
std::bitset<32> bit_set(number);
return (bit_set.count()<2);
}
[C++] Fast Power of 2 Test
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:
Is this method effecient or is there a faster way?
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.
Quote:Original post by Null and VoidQuote: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
!(a & (--a)) && a;
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.
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
Popular Topics
Advertisement