我正在寻找一种有效的方法(最好使用少量按位运算),它返回左移的计数或求解方程式:
找到给定y的x,其中y = 2 ^ x
例如(1 <&lt; 4)= 16 = 10000b。因此,如果给出16,我如何解决左移的量,在给定的情况下 4 。此外,我不正在寻找一种涉及循环或日志方法的方法,如:
unsigned int count_shift(unsigned int shifted)
{
unsigned int count = 0;
for (count = 0; shifted != 0x1; count++)
{
shifted /= 2;
}
return count;
}
干杯!
答案 0 :(得分:0)
除非你使用查询表 1 ,否则最快的已知方法是O(N):
unsigned int count = 0;
while (shifted >>= 1){
++count;
}
1 在某些芯片上评估exp
和log
的方式 - 牛顿Raphson型算法,其中查找表定义了某些功能点。
答案 1 :(得分:0)
如果数字保证为2的幂,即y == 1 << x
,则可以使用256字节的查找表和4个查找来完成:
static unsigned char lookup[256] = {
[0x01]=1, [0x02]=2, [0x04]=3, [0x08]=4, [0x10]=5, [0x20]=6, [0x40]=7, [0x80]=8
};
unsigned log2uint(unsigned y) {
unsigned res = lookup[(y >> 0) & 0xFF];
if (res) return res + 0 - 1;
res = lookup[(y >> 8) & 0xFF];
if (res) return res + 8 - 1;
res = lookup[(y >> 16) & 0xFF];
if (res) return res + 16 - 1;
res = lookup[(y >> 24) & 0xFF];
if (res) return res + 24 - 1;
return 0;
}
如果您不介意特定于供应商的功能,gcc会提供__builtin_ctz
函数,该函数返回尾随零的数量,该值与y == 1 << x
(Demo 2)时获得的返回值相匹配