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 hochl for What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

$
0
0

I know I am massively late to the party, but I just came across this question and I wanted to share my template solution for getting the highest bit that is set in the argument as a value and not the exponent, i.e. not the number 4 but the value 2^4 = 16 if bit 4 is the highest bit that is set. This function can be used for any numeric type:

template<typename T>                                                            T top_bit(T n)                                                                  {                                                                                   T ret;                                                                          do {                                                                                ret = n;                                                                        n &= n - 1;                                                                 } while (n);                                                                    return ret;                                                                 }  

It works by remembering the last value and eliminating the lowest bit until no bit is left. Thus, the last value is the one with the highest bit set. An argument of zero will return 0.


Viewing all articles
Browse latest Browse all 36

Trending Articles



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