如何确定需要两个值的功率权位的移位数? [英] How to determine the number of right bit-shifts needed for a power of two value?
问题描述
我有一个接收两个值的功率的函数。
I have a function that receives a power of two value.
我需要将其转换为一个枚举范围(0,1,2,3,等等),然后移回两个范围的功率
I need to convert it to an enum range (0, 1, 2, 3, and so on), and then shift it back to the power of two range.
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
... and so on.
如果我的函数接收1024的值,我需要将其转换为10.什么是在C#中做到这一点的最好方法是什么?如果我只是在一个循环中不断分裂2和计数迭代?
If my function receives a value of 1024, I need to convert it to 10. What is the best way to do this in C#? Should I just keep dividing by 2 in a loop and count the iterations?
我知道我可以把它带回(1<< 10)。
I know I can put it back with (1 << 10).
推荐答案
只需使用基地2的对数:
Just use the logarithm of base 2:
Math.Log(/* your number */, 2)
例如,将Math.log(1024,2)
返回10。
更新:
下面是一个相当可靠的版本来检查,如果传入的数量是二的幂:
Here's a rather robust version that checks if the number passed in is a power of two:
public static int Log2(uint number)
{
var isPowerOfTwo = number > 0 && (number & (number - 1)) == 0;
if (!isPowerOfTwo)
{
throw new ArgumentException("Not a power of two", "number");
}
return (int)Math.Log(number, 2);
}
为号检查
正二的幂是从的 http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
有更多的技巧,在该页面上找到一个整数LOG2,从这里开始:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious一>
There are more tricks to find log2 of an integer on that page, starting here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
这篇关于如何确定需要两个值的功率权位的移位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!