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

$
0
0

A version in C using successive approximation:

unsigned int getMsb(unsigned int n){  unsigned int msb  = sizeof(n) * 4;  unsigned int step = msb;  while (step > 1) {    step /=2;    if (n>>msb)     msb += step;   else     msb -= step; }  if (n>>msb)    msb++;  return (msb - 1);}

Advantage: the running time is constant regardless of the provided number, as the number of loops are always the same.( 4 loops when using "unsigned int")


Viewing all articles
Browse latest Browse all 36

Trending Articles



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