简体   繁体   English

如何使用按位运算符计算对数基数 2?

[英]How to compute log base 2 using bitwise operators?

I need to compute the log base 2 of a number in C but I cannot use the math library.我需要计算 C 中数字的对数基数 2,但我不能使用数学库。 The answer doesn't need to be exact, just to the closest int.答案不需要很精确,只需要最接近的 int。 I've thought about it and I know I could just use a while loop and keep dividing the number by 2 until it is < 2, and keep count of the iterations, but is this possible using bitwise operators?我已经考虑过了,我知道我可以只使用一个while循环并继续将数字除以2直到它<2,并保持迭代计数,但是这可以使用按位运算符吗?

Already answered by abamert but just to be more concrete this is how you would code it: abamert 已经回答了,但更具体地说,这就是你将如何编码它:

Log2(x) = result
while (x >>= 1) result++;   

If you count shifting as a bitwise operator, this is easy.如果将移位算作按位运算符,这很容易。

You already know how to do it by successive division by 2.您已经知道如何通过连续除以 2 来做到这一点。

x >> 1 is the same as x / 2 for any unsigned integer in C.对于 C 中的任何无符号整数, x >> 1x / 2相同。

If you need to make this faster, you can do a "divide and conquer"—shift, say, 4 bits at a time until you reach 0, then go back and look at the last 4 bits.如果你需要让它更快,你可以做一个“分而治之”——一次移动 4 位,直到你达到 0,然后返回并查看最后 4 位。 That means at most 16 shifts and 19 compares instead of 63 of each.这意味着最多 16 个班次和 19 个比较,而不是每个班次 63 个。 Whether it's actually faster on a modern CPU, I couldn't say without testing.在现代 CPU 上它是否真的更快,我不能说没有测试。 And you can take this a step farther, to first do groups of 16, then 4, then 1. Probably not useful here, but if you had some 1024-bit integers, it might be worth considering.你可以更进一步,先做 16 组,然后是 4 组,然后是 1 组。在这里可能没用,但如果你有一些 1024 位整数,可能值得考虑。

__builtin_clz(x): This function is used to count the leading zeros of the integer. __builtin_clz(x):这个 function 用于计算 integer 的前导零。 Note: clz = count leading zero's (In C/ C++).注意:clz = 计数前导零(在 C/C++ 中)。 Considering 32 bit Integer,考虑到 32 位 Integer,

log_2_x = 32 - __builtin_clz(x) - 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM