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

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

$
0
0

I assume your question is for an integer (called v below) and not an unsigned integer.

int v = 612635685; // whatever value you wishunsigned int get_msb(int v){    int r = 31;                         // maximum number of iteration until integer has been totally left shifted out, considering that first bit is index 0. Also we could use (sizeof(int)) << 3 - 1 instead of 31 to make it work on any platform.    while (!(v & 0x80000000) && r--) {   // mask of the highest bit        v <<= 1;                        // multiply integer by 2.    }    return r;                           // will even return -1 if no bit was set, allowing error catch}

If you want to make it work without taking into account the sign you can add an extra 'v <<= 1;' before the loop (and change r value to 30 accordingly).Please let me know if I forgot anything. I haven't tested it but it should work just fine.


Viewing all articles
Browse latest Browse all 36

Trending Articles



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