Royce Mitchell III wrote:
Mike Nordell wrote:
int highest_bit(unsigned int i) { int temp; int ret = 0; temp = i > 0xffff; i >>= 16*temp; ret = 16*temp; temp = i > 0xff; i >>= 8*temp; ret += 8*temp; temp = i > 0xf; i >>= 4*temp; ret += 4*temp; temp = i > 0x3; i >>= 2*temp; ret += 2*temp; ret += (i>>1); return ret; }
This is almost, but not quite, 50% slower in msvc6 w/ "compile for speed". :(
Perhaps the reordering could help...
FWIW, I also came up with the following code last night, which was only a hair slower than the code I sent to Alex, but perhaps might lend itself to speed-up better?
int highest_bit_v3 ( unsigned int i ) { int ret = 0; int n = i >> 16; if ( n ) i = n, ret = 16; n = i >> 8; if ( n ) i = n, ret += 8; n = i >> 4; if ( n ) i = n, ret += 4; n = i >> 2; if ( n ) i = n, ++ret, ++ret; return ret + (i>>1); }