是否有任何快速算法来计算所有为 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实现,已经回答过了
关于c - 是否有任何快速算法来计算所有 2 的幂的数字的 log2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328489/