Jump to content
  • Advertisement
Sign in to follow this  
Gondolin

[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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
int a;

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

Share this post


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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
int a;

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


a &(a-1) == 0

(1000 & 0111)==0000

Share this post


Link to post
Share on other sites
!(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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!