Powers of 2

Started by
4 comments, last by Marty666 21 years, 1 month ago
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
_____ /____ /|| | || MtY | ||_____|/Marty
Advertisement
last bit should be zero, cause 2^0 doesn''t count in my prog...

Marty
_____ /____ /|| | || MtY | ||_____|/Marty
const bool isPowerOf2(int num){
return (num!=0) && ((num&(num-1))==0);
}


emptyhead
Watch out for advice from the successfull, they don''t want company
:wq!
// 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
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!
_____ /____ /|| | || MtY | ||_____|/Marty

This topic is closed to new replies.

Advertisement