# Thread: power of 2? without loops or recursion

1. ## power of 2? without loops or recursion

Hi,
I read this question somewhere and also found its answer on the web but couldnt figure it out. can anyone pls enlighten me:

Ques:
Test if an unsigned integer is a power of two without loops or recursion?

Soln: #define power_of_two(x) \ ((x)&&(~(x&(x-1))))

Can anyone figure out what is this macro doing?
Pls try to simplify ur explanation as much as possible.

Thanks.

2. Here's a little different code for the same thing:

Code:
#define power_of_two(x) ((x & (x - 1)) == 0);
Returns 1 is it is a power of two, zero otherwise. The code changes the least significant bit of x to zero, and if x is a power of two then after the statement (x & (x - 1)) there is only one bit with a value of one and if you set it to zero it leaves you with zero for the answer.

3. ## Thanks

Hey Entropic,
Thanks a lot for the code and the explanation.

4. #define PTWO(x) (x%2==0)

Quzah.

5. Originally posted by quzah
#define PTWO(x) (x%2==0)

Quzah.
Nono, that checks whether the number is odd or even, you little brat

6. Originally posted by Magos
Nono, that checks whether the number is odd or even, you little brat
Yeah. I was thinking if it was a multiple of two, not a power of...

Quzah.

7. Since the quick way has been done for you, I'll give you a different way:
Code:
#define pot_test(x) \
( \
x==(1<<1) || \
x==(1<<2) || \
x==(1<<3) || \
x==(1<<4) || \
x==(1<<5) || \
x==(1<<6) || \
x==(1<<7) || \
x==(1<<8) || \
x==(1<<9) || \
x==(1<<10) || \
x==(1<<11) || \
x==(1<<12) || \
x==(1<<13) || \
x==(1<<14) || \
x==(1<<15) || \
x==(1<<16) || \
x==(1<<17) || \
x==(1<<18) || \
x==(1<<19) || \
x==(1<<20) || \
x==(1<<21) || \
x==(1<<22) || \
x==(1<<23) || \
x==(1<<24) || \
x==(1<<25) || \
x==(1<<26) || \
x==(1<<27) || \
x==(1<<28) || \
x==(1<<29) || \
x==(1<<30) || \
x==(1<<31)    \
)
Unlike the first example, mine will work on floating point numbers. Neither example will work on negative numbers.

Quzah.

8. You forgot 1. 2^0 = 1.

9. Originally posted by Magos
You forgot 1. 2^0 = 1.
I actually intentionally left it out.

Quzah.

Popular pages Recent additions