[LCP]Base 2 logarithms

Chuck Martin nrocinu at myrealbox.com
Thu Oct 3 19:46:01 UTC 2002


On Thu, Oct 03, 2002 at 10:35:00AM +0100, Vincent Penquerc'h wrote:
> > What's the best way to calculate base 2 logarithms?  I know 
> > that I could
> > use log(x)/log(2) or log10(x)/log10(2), but I'm not sure 
> 
> Of an int ?

No, a double.

> If not an int, then floor it, and get the int, then:
> 
> unsigned int log2(unsigned int n)
> {
>   int l=0;
>   while (n) {
>     n>>=1;
>     ++l;
>   }
>   return n;
> }

This won't work for numbers less than zero (negative logarithms).
Also, it only gives the integer part of the logarithm, which for
my current needs doesn't really matter, but would be nice to know,
nevertheless.

Chuck




More information about the linuxCprogramming mailing list