log2(n)进行位操作
我试图找出如何找到二进制数字的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 */
我只是想知道如何在不使用循环的情况下获得最重要位的位置!
谢谢!
链接地址: http://www.djcxy.com/p/36399.html