Archived

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

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.

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 on other sites
last bit should be zero, cause 2^0 doesn''t count in my prog...

Marty

Share on other sites
// 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 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.69314718bool 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.69314718int 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]

thanx all!

1. 1
2. 2
Rutin
23
3. 3
JoeJ
20
4. 4
5. 5

• 27
• 40
• 23
• 13
• 13
• Forum Statistics

• Total Topics
631737
• Total Posts
3001944
×