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
  • 37,963
  • 15
  • 156
  • 475
07012220
  • 85
  • 1
  • 7
  • 1
    Take a look at http://stackoverflow.com/questions/15508319/calling-a-generic-method-with-t-type-parameter – erictrigo 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
  • 14,734
  • 5
  • 67
  • 101
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,704
  • 12
  • 15
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
  • 37,963
  • 15
  • 156
  • 475