c - 是否有任何快速算法来计算所有 2 的幂的数字的 log2?

标签 c algorithm math

是否有任何快速算法来计算所有为 2 的幂的数字的 log2,例如:

log2(1), log2(2), log2(4), log2(1024), log2(4096)...

我正在考虑用它来实现位集迭代。

最佳答案

假设您知道数字必须是 2 的幂,所以在二进制中,它是 1 后跟 n 0 其中 n 是您要查找的数字。

如果您使用的是 gcc 或 clang,您可以使用 builtin function

— Built-in Function: int __builtin_ctz (unsigned int x)

Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.

对于纯C实现,已经回答过了

Finding trailing 0s in a binary number

关于c - 是否有任何快速算法来计算所有 2 的幂的数字的 log2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328489/

相关文章:

c - 如何索引障碍分配

c - 多播不工作

r - 多元 t 混合模型的 EM 算法

algorithm - 在固定长度的输入上证明完美的哈希函数

performance - 稀疏矩阵乘法的特例

c++ - OpenGL/GLM - 切换坐标系方向

c - SQLite C API,可以打开数据库但不使用查询返回任何数据吗?

c - 在 GCC 中以编程方式调用调试器

algorithm - 区域优化算法

ruby - 如何在 Ruby 中将数字数组转换为矩阵