如何获得下一个更高的 2 次方

本文关键字:次方 何获得 下一个 | 更新日期: 2023-09-27 18:35:20

我想将以下 Matlab 代码转换为 C#:

nfft=2^nextpow2(nn);

其中 NEXTPOW2(N) 表示 Matlab 中 2 的下一个更高幂。

那么我们如何在 C# 代码中自己或通过 ilnumerics Lab 的帮助来实现相同的功能呢?

如何获得下一个更高的 2 次方

这可能是最有效的方法,之前在SO上也提到过:

unsigned int v; // compute the next highest power of 2 of 32-bit v
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
如果我

正确理解你的问题:

x = 129;
NextPow = round(2^ceil(log2(x))) % Gives 256 for x = 129
                                 % Gives 2 for x = 2
                                 % Gives 16 for x = 15

在 .NET Core 中,您可以使用 BitOperations.LeadingZeroCount()BitOperations.Log2() 来获取最高有效位的位置,然后

return 1L << (BitOperations.Log2(nn - 1) + 1); // or
return 1L << (63 - BitOperations.LeadingZeroCount(nn));

如果nn ulong.如果uint nn,请将 63 更改为 31

上述位操作是映射到硬件指令的内在操作,因此它们非常快