2010-11-13 11 views
2

Quelle est une bonne routine de bit-twiddling pour convertir un nombre dans la gamme [2^N, 2^(N-1) -1] en N?Bit twiddling en C: comment convertir 2^N en N?

Quelques exemples:

  • f (1) -> 0
  • f ([2-3]) -> 1
  • f ([4-7]) -> 2
  • f ([8-15]) -> 3

Voici une mise en œuvre:

uint f(uint num) 
{ 
    for (uint shifts = 0; num; shifts++) 
     num >>= 1; 
    return (shifts - 1); 
} 
+0

http://en.wikipedia.org/wiki/Binary_logarithm – kennytm

+0

double possible de [Comment obtenir lg2 d'un nombre qui est 2^k] (http://stackoverflow.com/questions/2213825/ comment-obtenir-lg2-d'-un-nombre-que-est-2k) – kennytm

+0

voulez-vous dire "gamme [2^N-1, 2^(N-1)]"? – pmg

Répondre

3

Comme approche la plus générale, la recherche binaire peut aider. Pour les valeurs 0..31, il suffit de 5 étapes.

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;