C has a built-in function for this: __builtin_clz() (count leading zeros ); it should use special instructions if the particular CPU happens to have them (ARM CM3 has a "clz" instruction (by CM0 doesn't!)), or do the loop (or perhaps some other "better" algorithm) if not. There are similar built-in functions for finding the first one from the LSB.