In your case since you know only one bit is set, so it's enough to count trailing zeros. This can be done without a hardware instruction very quickly. Check out this answer, that's where the code below comes from (I'm not one to tamper with perfection... sometimes).
unsigned v; // this is the number with one bit set
unsigned r; // this becomes the exponent in v == pow(2, r)
static const unsigned MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((unsigned)((v & -v) * 0x077CB531U)) >> 27];
In your case since v
only has one bit set, so you don't need to find the lowest bit set; therefore you can skip v & -v
. And your version of the code becomes this:
unsigned v; // this is the number with one bit set
unsigned r; // this becomes the exponent in v == pow(2, r)
static const unsigned MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[(v * 0x077CB531U) >> 27];
See the link for more information, it in turn links to it's source information.