Assuming you're on x86 and game for a bit of inline assembler, Intel provides a BSR
instruction ("bit scan reverse"). It's fast on some x86s (microcoded on others). From the manual:
Searches the source operand for the most significant set bit (1 bit). If a most significant 1 bit is found, its bit index is stored in the destination operand. The source operand can be a register or a memory location; the destination operand is a register. The bit index is an unsigned offset from bit 0 of the source operand. If the content source operand is 0, the content of the destination operand is undefined.
(If you're on PowerPC there's a similar cntlz
("count leading zeros") instruction.)
Example code for gcc:
#include <iostream>int main (int,char**){ int n=1; for (;;++n) { int msb; asm("bsrl %1,%0" : "=r"(msb) : "r"(n)); std::cout << n << " : "<< msb << std::endl; } return 0;}
See also this inline assembler tutorial, which shows (section 9.4) it being considerably faster than looping code.