
13 Jul
2010
13 Jul
'10
11:04 a.m.
Tim Blechmann wrote:
hi all,
i am aware, that boost provides a compile-time integer log2 function. but what is the best way to compile an integer log2 at run-time?
In the good'ol Bits Twiddling Hacks page: unsigned int v; // 32-bit value to find the log2 of unsigned int r; // result of log2(v) will go here unsigned int shift; r = (v > 0xFFFF) << 4; v >>= r; shift = (v > 0xFF ) << 3; v >>= shift; r |= shift; shift = (v > 0xF ) << 2; v >>= shift; r |= shift; shift = (v > 0x3 ) << 1; v >>= shift; r |= shift; r |= (v >> 1); We use a similar stuff in NT². I can be obviously fitted back to 16 and 8 bits integer for more speed.