實在懶得打字…,反正結論就是我用3.,就這樣XD
1. x越大, 則迴圈執行次數越多, 效能隨x變動
int IntLog2(unsigned int x)
{
int r = 0;
while (x > 1)
{
x >>= 1;
++r;
}
return r;
}
2. 概念是二分搜尋, 效能中等
int IntLog2(unsigned
int x)
{
int f = 0, s = 32;
while (s)
{
int f = 0, s = 32;
while (s)
{
s >>= 1;
if( x >= 1<<(f+s) ) f+=s;
}
return f;
}
s >>= 1;
if( x >= 1<<(f+s) ) f+=s;
}
return f;
}
3. 相當簡單又易懂的方式, 整體來說我建議採用這個
int IntLog2(unsigned int x)
{
int r = 0;
if (x >= (65536)) { x >>= 16; r |= 16; }
if (x >= ( 256)) { x >>= 8; r |= 8; }
if (x >= ( 16)) { x >>= 4; r |= 4; }
if (x >= ( 4)) { x >>= 2; r |= 2; }
if (x >= ( 2)) { r |= 1; }
return r;
}
4. 使用組合語言, 意外的是效能並沒有比3.來的好
int IntLog2Asm(unsigned int x)
{
__asm {
bsr eax, x
}
}
全站熱搜