log2 not found in my math.h?

Solution 1:

From here:

Prototype: double log2(double anumber);
Header File: math.h (C) or cmath (C++)

Alternatively emulate it like here

#include <math.h>  
...  
// Calculates log2 of number.  
double Log2( double n )  
{  
    // log(n)/log(2) is log2.  
    return log( n ) / log( 2 );  
}  

Unfortunately Microsoft does not provide it.

Solution 2:

log2() is only defined in the C99 standard, not the C90 standard. Microsoft Visual C++ is not fully C99 compliant (heck, there isn't a single fully C99 compliant compiler in existence, I believe -- not even GCC fully supports it), so it's not required to provide log2().

Solution 3:

If you're trying to find the log2 of strictly integers, some bitwise can't hurt:

#include <stdio.h>

unsigned int log2( unsigned int x )
{
  unsigned int ans = 0 ;
  while( x>>=1 ) ans++;
  return ans ;
}

int main()
{
  // log(7) = 2 here, log(8)=3.
  //for( int i = 0 ; i < 32 ; i++ )
  //  printf( "log_2( %d ) = %d\n", i, log2( i ) ) ;

  for( unsigned int i = 1 ; i <= (1<<30) ; i <<= 1 )
    printf( "log_2( %d ) = %d\n", i, log2( i ) ) ;
}