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;}