0

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.?

phuclv
  • 32,499
  • 12
  • 130
  • 417
07012220
  • 85
  • 1
  • 7
  • 1
    Take a look at http://stackoverflow.com/questions/15508319/calling-a-generic-method-with-t-type-parameter – Antrim Feb 18 '16 at 08:57

3 Answers3

5

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++;
Community
  • 1
  • 1
Ofek Shilon
  • 13,332
  • 5
  • 59
  • 95
1

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
RPM
  • 1,648
  • 12
  • 14
0

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

phuclv
  • 32,499
  • 12
  • 130
  • 417