ok so im anal but i had to try this. i am dubious of my performance counter method, but it shows it to be about 33% faster than a sequential loop.
#define SETBIT( bit) ( ( 0x00000001 << bit ) )
#define BITON( bit, v) ( SETBIT( bit) & v )
// return true if the bit is the most significant in lval
#define MSB( bit, lval) ( BITON( bit, lval) && SETBIT( bit + 1) > lval )
// most significant bit one based
int msb( unsigned long lval){
if( !lval) return 0;
if( lval & 0x80000000) return 32;
int upper = 31, lower = 0, pos = 16, msb = 0;
while( !msb){
// check this bit
if( MSB(pos, lval) ) msb = pos + 1;
// check left and right
else if( MSB((pos + 1), lval) ) msb = pos + 2;
else if( MSB( (pos -1), lval) ) msb = pos;
else if( SETBIT(pos) < lval){ // position is less than the most significant bit
lower = pos;
pos += ((upper - lower) / 2);
}else{ // position is greater than the most significant bit
upper = pos;
pos -= ((upper - lower) / 2);
}
}
return msb;
}
-There are only 10 types of people in the world, those who understand binary and those who don't-
-pete