In the equation :
What is the fastest way in C language to find x with a given power of two value (a) ?
Edit :
- The mathematical exact solution is :
- As (a) is a positive integer and a power of two (no rational number, no equal to zero), this problem can be simplified as "looking for position of set bit".
- This post is focused on lite embedded CPU systems. For example : ARM CORTEX M4.
a to x results :
a | x
-------
1 | 0
2 | 1
4 | 2
8 | 3
16 | 4
32 | 5
64 | 6
128 | 7
256 | 8
512 | 9
...
Option 1 : The dirty loop
unsigned int get_power_of_two_exponent(unsigned int value)
{
unsigned int x = 0;
while( ( 1 << x ) != value)
{
x ++;
}
return x;
}
Option 2 : The weird trick
#include <stdint.h>
#if defined(__GNUC__)
static int highest_bit_set(uint32_t value)
{
if (sizeof (unsigned int) == sizeof value)
return 31 - __builtin_clz(value);
else
if (sizeof (unsigned long) == sizeof value)
return 31 - __builtin_clzl(value);
else
exit(127); /* Weird architecture! */
}
#endif
Any faster options ?