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

$
0
0

thats some kind of binary search, it works with all kinds of (unsigned!) integer types

#include <climits>#define UINT (unsigned int)#define UINT_BIT (CHAR_BIT*sizeof(UINT))int msb(UINT x){    if(0 == x)        return -1;    int c = 0;    for(UINT i=UINT_BIT>>1; 0<i; i>>=1)    if(static_cast<UINT>(x >> i))    {        x >>= i;        c |= i;    }    return c;}

to make complete:

#include <climits>#define UINT unsigned int#define UINT_BIT (CHAR_BIT*sizeof(UINT))int lsb(UINT x){    if(0 == x)        return -1;    int c = UINT_BIT-1;    for(UINT i=UINT_BIT>>1; 0<i; i>>=1)    if(static_cast<UINT>(x << i))    {        x <<= i;        c ^= i;    }    return c;}

Viewing all articles
Browse latest Browse all 36

Trending Articles



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