I want transform the following Matlab code to C#:
nfft=2^nextpow2(nn);
where NEXTPOW2(N)
means the next higher power of 2 in Matlab.
So how do we achieve the same function by ourselves in C# code or by the help of ilnumerics Lab.?
I want transform the following Matlab code to C#:
nfft=2^nextpow2(nn);
where NEXTPOW2(N)
means the next higher power of 2 in Matlab.
So how do we achieve the same function by ourselves in C# code or by the help of ilnumerics Lab.?
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++;
If I understand your question correctly:
x = 129;
NextPow = round(2^ceil(log2(x))) % Gives 256 for x = 129
% Gives 2 for x = 2
% Gives 16 for x = 15
In .NET Core you can use BitOperations.LeadingZeroCount()
or BitOperations.Log2()
to get the most significant bit's position and then
return 1L << (BitOperations.Log2(nn - 1) + 1); // or
return 1L << (63 - BitOperations.LeadingZeroCount(nn));
if nn
is ulong
. Change 63 to 31 if nn
is uint
The above bit operations are intrinsics that are mapped to hardware instructions so they're extremely fast