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

$
0
0

One more way to achieve this using the same idea of branchless binary search has for future reference.

This iteration seems to unroll on most compilers and compile options I've been testing on Godbolt and speed wise it is very much the same as already mentioned while val >>= 1 loops.

static int msb(uint x) {  int pos = 0;  int len = 16;  for (; len ; len >>= 1) {    pos += ((x & ((1 << (pos + len - 1)) - 1)) < x) * len;  }  return pos;}

But it's been nice to see how well the loop contents optimise into few instructions per iteration during the compilation. And the whole branchless binary search has been all-in-all an interesting idea to utilise for other purposes too.


Viewing all articles
Browse latest Browse all 36

Trending Articles



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