If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of
thats some kind of binary search, it works with all kinds of (unsigned!) integer types
#include
#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>=1)
if(static_cast(x >> i))
{
x >>= i;
c |= i;
}
return c;
}
to make complete:
#include
#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>=1)
if(static_cast(x << i))
{
x <<= i;
c ^= i;
}
return c;
}