Search code examples
c#matlabilnumerics

How to get the next higher power of 2?


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


Solution

  • 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++;