c - 使用C查找log2的优化方法

标签 c algorithm arm

我正在寻找一种有效的方法(最好使用少量位运算),该方法返回左移计数或将方程解为:

find x for a given y where y=2^x

例如 (1 << 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;
}

干杯!

最佳答案

如果保证该数字是2的幂,即y == 1 << x ,您可以使用 256 字节的查找表和四个查找来完成:

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;
}

Demo 1

如果您不介意供应商特定的功能,gcc 提供 __builtin_ctz返回尾随零的数量的函数,它与 y == 1 << x 时获得的返回值匹配(Demo 2)

关于c - 使用C查找log2的优化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46429831/

相关文章:

c++ - 按位运算的意外结果为什么 (1 | 1 & 2) 给出 1 而不是 2?

algorithm - 符号状态探索在符号模型检查中的工作原理

mono - 无法为 ARM 交叉编译 Mono

algorithm - 在图的生成树中找到最大比率最小切割

编译时的 C 数组对齐检查

c++ - 在 C++ 中编写外部程序以与 wpa_supplicant 交互

c - null 终止字符串数组

c - Windows PE 结构中的管理进程位

在函数内部更改堆栈上的结构

c - 直接在二维数组中执行 fisher - yates shuffle