# Thread: Determining what power of 2 a number is without loops

1. ## Determining what power of 2 a number is without loops

For example 2^5 is 32, so given the input 32, the result would be 5. I know I could do this like:

while( num > 0 ) num >>= 1;

but I was wondering if there was some bit operation or something because I'd rather not use a loop for this particular situation. 2. 2^a = b <=> log_2(b) = a
log_2(x) = log(x)/log(2) 3. > because I'd rather not use a loop for this particular situation.
Why ever not?
I mean, it's only one line of code and with a max of 32 iterations, it's bound to be a lot quicker than any contrived "loop-free" answers (which will actually contain vastly more complex loops, just hidden from view that's all). 4. Here's a bona fide loop-free answer. It might be quicker for some inputs, but obviously slower for 1, 2, 4, 8, 16. May be faster for something like 128 or 256 and higher.

Code:
```int pow = 0;
unsigned long tmp;
/* Let's assume num is an unsigned long; assume
unsigned longs are 32 bits :-) */

if (tmp = num >> 16) {
pow |= 16;
num = tmp;
}
if (tmp = num >> 8) {
pow |= 8;
num = tmp;
}
if (tmp = num >> 4) {
pow |= 4;
num = tmp;
}
if (tmp = num >> 2) {
pow |= 2;
num = tmp;
}
if (tmp = num >> 1) {
pow |= 1;
num = tmp;
}
/* pow now contains the logarithm. */```
Of course, you could just roll that into a loop:
Code:
```int pow = 0;
unsigned long tmp; /* Should really be same type as num. */
int i = 32; /* Set to power of two, >= length of num in bits. */
while (i >>= 1) {
if (tmp = num >> i) {
pow |= i;
num = tmp;
}
}``` 5. Originally Posted by Sfpiano
For example 2^5 is 32, so given the input 32, the result would be 5. I know I could do this like:

while( num > 0 ) num >>= 1;

but I was wondering if there was some bit operation or something because I'd rather not use a loop for this particular situation.
You're looking to find an exponent dear. You should probably use logarithms. You want to know the exponent in 2^x = y. Let's use your 32 for our y. So 2^x = 32. Since log functions do not allow you to specify bases other than 10 or e, you have to use the change of base method:

log(total) / log(new base) = log _new base(32)

log(32) / log (2) solves for the exponent. Try it yourself. It'll always work for any base, total, etc. It works great for determining exponential growth in RPG-game characters too.  Popular pages Recent additions 