如何获得 2 的下一个更高次方?
How to get the next higher power of 2?
我想将以下 Matlab 代码转换为 C#:
nfft=2^nextpow2(nn);
其中 NEXTPOW2(N)
表示 Matlab 中 2 的下一个更高次幂。
那么我们如何自己用C#代码或者借助ilnumerics Lab实现同样的功能呢?
如果我正确理解你的问题:
x = 129;
NextPow = round(2^ceil(log2(x))) % Gives 256 for x = 129
% Gives 2 for x = 2
% Gives 16 for x = 15
This is probably the most efficient way, also previously mentioned here on 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++;
在 .NET Core 中,您可以使用 BitOperations.LeadingZeroCount()
or BitOperations.Log2()
获取最高有效位,然后
return 1L << (BitOperations.Log2(nn - 1) + 1); // or
return 1L << (63 - BitOperations.LeadingZeroCount(nn));
如果 nn
是 ulong
。如果 nn
是 uint
,则将 63 更改为 31
以上位操作是映射到硬件指令的内部函数,因此它们非常快
我想将以下 Matlab 代码转换为 C#:
nfft=2^nextpow2(nn);
其中 NEXTPOW2(N)
表示 Matlab 中 2 的下一个更高次幂。
那么我们如何自己用C#代码或者借助ilnumerics Lab实现同样的功能呢?
如果我正确理解你的问题:
x = 129;
NextPow = round(2^ceil(log2(x))) % Gives 256 for x = 129
% Gives 2 for x = 2
% Gives 16 for x = 15
This is probably the most efficient way, also previously mentioned here on 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++;
在 .NET Core 中,您可以使用 BitOperations.LeadingZeroCount()
or BitOperations.Log2()
获取最高有效位,然后
return 1L << (BitOperations.Log2(nn - 1) + 1); // or
return 1L << (63 - BitOperations.LeadingZeroCount(nn));
如果 nn
是 ulong
。如果 nn
是 uint
以上位操作是映射到硬件指令的内部函数,因此它们非常快