2010-11-13 71 views
2

將範圍[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); 
} 
+0

http://en.wikipedia.org/wiki/Binary_logarithm的 – kennytm 2010-11-13 18:25:34

+0

可能重複的[如何獲得一個數字,是的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

+0

你的意思是「範圍[2^N-1,2 ^(N-1)]」? – pmg 2010-11-13 18:31:05

回答

3

作爲最普遍的方法,二分查找可能有所幫助。對於值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; 
相關問題