Skip to main content
 首页 » 编程设计

c#之更快的 Log2Ceil

2024年02月20日11pander-it

我想知道是否有人知道一种更快的方法来实现下面的函数,即在 C# 中计算整数上限 2 的对数。

private int Log2Ceil(int x) 
{ 
   return (int)Math.Ceiling(Math.Log((double)x, 2)); 
} 

请您参考如下方法:

查看 this question 的答案.它引用的代码是用 C 编写的,但大部分代码也适用于 C#。

或者,您可以使用

private int Log2Ceil(int n) { 
    long bits = BitConverter.DoubleToInt64Bits((double)n); 
    return ((int)(bits >> 52) & 0x7ff) - 1022; 
} 

它利用了 float 包含二进制指数编码这一事实。快速基准测试表明,这比 x64 上的原始速度快 13 倍,在 x86 上快约 21 倍。