I want to find the most significant bit that is set to 1
. I have tried every possible way from &
to ORing all of the bits from 1
t
The slickest implementation I've come across - three iterations and a table lookup.
unsigned int msb32(unsigned int x)
{
static const unsigned int bval[] =
{ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
unsigned int base = 0;
if (x & 0xFFFF0000) { base += 32/2; x >>= 32/2; }
if (x & 0x0000FF00) { base += 32/4; x >>= 32/4; }
if (x & 0x000000F0) { base += 32/8; x >>= 32/8; }
return base + bval[x];
}