Quantcast
Channel: What is the fastest/most efficient way to find the position of the highest set bit (msb) in an integer in C? - Stack Overflow
Viewing all articles
Browse latest Browse all 73

Answer by Richard Keene for What is the fastest/most efficient way to find the position of the highest set bit (msb) in an integer in C?

$
0
0

My Fave.

    int logBase2_U16(unsigned short x) {        int result = 0;        if (x >= 256) { x >>= 8; result += 8; }        if (x >= 16) { x >>= 4; result += 4; }        if (x >= 4) { x >>= 2; result += 2; }        if (x >= 2) { result += 1; }        return result;    }

Easily extends to 32 and 64 bits. Returns 0 if x is 0.


Viewing all articles
Browse latest Browse all 73

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>