I follow the principle of never optimise unless you have to, and then when you do make it as specific as possible. I would make a few comments. First if possible write your code knowing the number of bits you number has, second if it makes sense avoid error checking, third do the smallest amount of work and then get out of there.
So with that in mind I would
find the location of the highest bit, don't worry about any other bits or if there are more than two. I would also assume that the integer is a 16-bit number.
I would then use ta0kira's approach but reverse it, that is look for the largest bit first, additionally I'd use literals rather than constants. I would also remove the error checking and break out as soon as the condition has been met.
This would give something like:
Code:
int posn = 0;
if (val & 65536)
posn = 16;
else if (val & 32768)
posn = 15;
else if (val & 16384)
posn = 14;
else if ...
Obviously you need to be sure that,
1) removing the error checking is acceptable,
posn = 0 if there are no bits set.
2) all the bits are accounted for,
adjusting the code appropriately
Metric of the algorithm, whilst big O is traditionally used to measure the efficiency of an algorithm, it only make sense when extrapolated to large numbers, here it is a small piece of data that is being examined and the
fixed number of instructions per iteration do make an impact on the overall efficiency.