2017
07
06
19
38
[C] Find the highest order bit
今天在網路上看到一篇用C實作 "32 位元整數的最高位位元位置",
然後原理是寫Binary Search, 我怎麼看都看不懂, 這跟Binary Search有什麼關係.
寫個sample測一下, 結果也不對.
問了Google大神, 找到一篇 Find the highest order bit in C - Stack Overflow
這裡面講的就沒有問題.
unsigned int hibit(unsigned int n) {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return n - (n >> 1);
}
不過我也順便看懂這個原理.
是利用bitwise or, 讓非0的最高bit以下的所有bits都變成1.
這也是為什麼最後需要做 n - ( n >> 1)
另外也可以用 n ^ ( n >> 1) 也可以有同樣效果.
也想到另外一招,
這是利用 (x & (x - 1)) == 0 就是 2^n, 變化出來的.
unsigned int test (unsigned int x)
{
unsigned int n;
while ((x & (x - 1)) != 0) {
x &= (x-1);
}
return x;
}