log2(n)带位操作

时间:2014-04-18 06:28:55

标签: bit-manipulation bit bitwise-operators

我正在试图弄清楚如何找到二进制数字的log2(n)。例如,我想以某种方式从01000中获得3(二进制中为8)。如何使用没有if语句或循环的位操作来执行此操作?它甚至可能吗?

这是我正在努力解决的问题:

howManyBits - return the minimum number of bits required to represent x in 2's complement                                                 
Examples:   howManyBits(12) = 5                                               
            howManyBits(298) = 10                                             
            howManyBits(-5) = 4                                               
            howManyBits(0)  = 1                                               
            howManyBits(-1) = 1                                               
            howManyBits(0x80000000) = 32                                      
Legal ops: ! ~ & ^ | + << >>   

到目前为止,我有这个:

int sign = x >> 31;

/* flip if negative */

int a = x ^ sign;

/* generate mask indicating leftmost 1 in a */

a = a | (a >> 1);
a = a | (a >> 2);
a = a | (a >> 4);
a = a | (a >> 8);
a = a | (a >> 16);
a = a ^ (a >> 1);

/* the amount of bits needed will be log2(a)+2 */ 

我不知道如何在不使用循环的情况下获得最重要位的位置!

谢谢!

0 个答案:

没有答案