My question is quite similar to Fastest way of computing the power that a "power of 2" number used?:
Giving x=2^y
as an input I want to output y
.
The difference is that I'm coding in C, not C++ and I know for sure that there is only one bit set in my input so I'm wondering if there is a more efficient ways to solve this.
Here is my try:
unsigned int get_power_of_two(unsigned int x)
{
unsigned int y=0;
for(unsigned int input=x; input>0; input=input>>1)
{
if(input & 1U)
{
break;
}
y++;
}
return y;
}
What is this efficiency compared to the proposed lookup table in @Dave's answer ?
(again, I'm coding in C so I don't have the iterators functions like lower_bound
)