將範圍[2^N,2 ^(N-1)-1]中的數字轉換爲N是一個很好的位扭曲程序是什麼?C:如何將2^N轉換爲N?
一些例子:
- F(1) - > 0
- F([2-3]) - > 1架
- F([4-7]) - > 2
- F([8-15]) - > 3
這裏是一個實現:
uint f(uint num)
{
for (uint shifts = 0; num; shifts++)
num >>= 1;
return (shifts - 1);
}
將範圍[2^N,2 ^(N-1)-1]中的數字轉換爲N是一個很好的位扭曲程序是什麼?C:如何將2^N轉換爲N?
一些例子:
這裏是一個實現:
uint f(uint num)
{
for (uint shifts = 0; num; shifts++)
num >>= 1;
return (shifts - 1);
}
根據數據類型的寬度以及可用內存的大小,查找表是一種可能性。這幾乎肯定是最快的方法。
有關其他方法,請參閱http://www-graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious及後續章節。
看看黑客用於計算基地2對數(或前導零計數,它們是相同的)這個頁面上:http://www-graphics.stanford.edu/~seander/bithacks.html
你也可以找到有用的功能__builtin_clz
(或_BitScanReverse
爲VS)用於x86 。
作爲最普遍的方法,二分查找可能有所幫助。對於值0..31,它只需要5個階段。
y = 0;
if(x >= 0x10000<<y) y += 0x10;
if(x >= 0x100<<y) y += 0x08;
if(x >= 0x10<<y) y += 0x04;
if(x >= 0x4<<y) y += 0x02;
if(x >= 0x2<<y) y += 0x01;
http://en.wikipedia.org/wiki/Binary_logarithm的 – kennytm 2010-11-13 18:25:34
可能重複的[如何獲得一個數字,是的LG2 2^K](http://stackoverflow.com/questions/2213825/ how-to-get-lg2-of-a-number-that-is-2k) – kennytm 2010-11-13 18:27:51
你的意思是「範圍[2^N-1,2 ^(N-1)]」? – pmg 2010-11-13 18:31:05