There are many other possibilities… Msb is essentially the same as log_2 function. So you could simply use the standard portable ilogb C99 function, that is, msb(v) == ilogb(v)+1. Except that this will fail in the special case of v==0.

Another solution relying on IEEE floating point standard is to cast the value to double (fast on modern computers) and then finding the exponent using bit magic:

int msb (unsigned v) {

union { double foo; unsigned long long x; } bar;

bar.foo = (double)(v) + 0.5;

return (bar.x >> 52) – 1023 + 1;

}

This is fast if (as always…) double is in ieee format and long long is 64 bit integer type (but you can use e.g. char array instead).

]]>