Advertisement

What's the quickest way to find if a number is power of 2?

Started by March 13, 2003 11:42 AM
13 comments, last by v_d_d 21 years, 11 months ago
What''s the quickest way to find if a given number is a power of 2?
Find out if log_2 is an integer.
GameDev Reader TODO List:1. Name my company.2. Buy domain name.3. Create web site.4. Name myself as CEO5. Create Game Engine.6. Design game.
Advertisement
log_2 ???
Yes, the base 2 logarithm.

log without subscript means base 10 logarithm.

ln means base e logarithm.

log_n (where _ denotes subscript) means base n logarithm.

So log_2 is a base 2 logarithm.
ok but how do I do this in the C language? The only functions I saw was log() and log10()...
I'd do:
int mask;int n = 0;for( mask = 1; mask != 0x80000000; mask <<= 1 ){    if( mask & nSomeInt )        n++;}if( n == 1 )    nSomeInt is a power of 2else    its not  



I am a signature virus. Please add me to your signature so that I may multiply.

[edited by - Enselic on March 13, 2003 1:24:13 PM]
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
Advertisement
If you want a log base 2 function here ya go:

double log2( double x ){   return ( log(x) / log( 2 ) );} 


The log of base N is defined as the natrual log of your number x divided by the natural log of the base you are looking for. In this case 2.

-SirKnight
I haven''t tested but I bet that my method is faster than using log...
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
Or for a more general log funtion:

double logn( double x, int base ){    return ( log( x ) / log( base ) );} 


Then you can just go:
double blah = logn( 15, 2 ); 


Or whatever.

-SirKnight
You''re probably right but I just wanted to throw that way of doing it in there to show how the log of whatever base is defined.

-SirKnight

This topic is closed to new replies.

Advertisement