Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Marty666

Powers of 2

This topic is 5617 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

Is there a simple way to find out if an (int) number is a power of 2? I know only one bit can be 1 and the last bit should be 0, but how do I find out in an easy function? Marty

Share this post


Link to post
Share on other sites
Advertisement
// checks if a number is a power of 2
BOOL IsPow2(int i)
{
// & the negative 2''s complement number with the passed param
// a power of 2 number will slip through
if ( (i & -i) == i ) return TRUE;
else return FALSE;
}// END IsPow2


There you go

Share this post


Link to post
Share on other sites
heres another way (the last one was good though):
given 2^y= z, if z is you number and it is a power of 2, y must be an int, or if y = lnz/ln2 (ln = log, you can use log10 - it doesn't matter). Note: z must be greater than 0.


    
#include <math.h>

#define LN_2 0.69314718

bool Power2(int value)
{
if(value <= 0)
reutrn false;
if( (log((double)value)/LN_2)%1 == 0)
return true;
else
return false;
}


you can also edit this funciton to return which power of two the number is, like so:


    
#include <math.h>

#define LN_2 0.69314718

int Power2(int value)
{
if(value <= 0)
reutrn 0;
float x;
x = float(log((double)value)/LN_2);
if( x%1 == 0)
return (int)x;
else
return 0;
}



[edited by - llvllatrix on March 2, 2003 11:49:29 AM]

Share this post


Link to post
Share on other sites

  • 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!