如何确定两个幂的幂所需的正确位移数?

Mic*_*yan 0 c# math bit-manipulation

我有一个功能,它接收两个值的功率.

我需要将它转换为枚举范围(0,1,2,3等),然后将其转换回两个范围的幂.

 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.
Run Code Online (Sandbox Code Playgroud)

如果我的函数接收到1024的值,我需要将其转换为10.在C#中执行此操作的最佳方法是什么?我应该在一个循环中继续除以2并计算迭代次数吗?

我知道我可以用(1 << 10)把它换回来.

And*_*ker 5

只需使用基数2的对数:

Math.Log(/* your number */, 2)
Run Code Online (Sandbox Code Playgroud)

例如,Math.Log(1024, 2)返回10.

更新:

这是一个相当强大的版本,用于检查传入的数字是否为2的幂:

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);
}
Run Code Online (Sandbox Code Playgroud)

检查是否为2 number的幂来自http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2

在该页面上有更多技巧可以找到整数的log2,从这里开始:http: //graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious