记录:
1. 自己的函数
int FastLog2(int x)
{
float fx;
unsigned long ix, exp;
fx = (float)x;
ix = *(unsigned long*)&fx;
exp = (ix >> 23) & 0xFF;
return exp - 127;
}
2. 使用库
数学中lg是10为地,ln是e为底。C里面log是e为底,log10以10为底,其余用换底公式: log(x)/log(2)。
3. 测试
#include "stdio.h"
#include "math.h"
int FastLog2(int x)
{
float fx;
unsigned long ix, exp;
fx = (float)x;
ix = *(unsigned long*)&fx;
exp = (ix >> 23) & 0xFF;
return exp - 127;
}
int main()
{
int result1;
int result2;
int x = 8;
result1 = FastLog2(x);
printf("The natural log of %d is %d\n", x, result1);
result2 = log(x)/log(2);
printf("The natural log of %d is %d\n", x, result2);
return 0;
}