08 August, 2005

Check if a number is a power of 2 the easier way

This one-liner does the trick...

((x != 0) && !(x & (x - 1)))

Clue : "every power of 2 has only one bit set in the binary representation"

8 comments:

Anil said...

think it can be made simpler with xor(hasa to think)

Unknown said...

give it a try ...

Anonymous said...

y do u check x!=0, if x=0, x-1 = -1 which will be represented as 11111111 which when ANDed with 00000000 will again give 0 :-)

Unknown said...

exactly... if x=0, then the expression will give 0 as the result indicating that 0 is a power of 2 which it is not.. thatz why the expression checks for (x != 0)

Music7 said...
This comment has been removed by the author.
Anonymous said...

example: 0x80000000

this is the number -2147483648...
we all know that no negative number is a power of 2

udhaya said...

//include math.h
void main()
{
int n,logval,powval;
printf("Enter a number to find whether it is s power of 2\n");
scanf("%d",&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf("The number is a power of 2");
else
printf("The number is not a power of 2");
getch();
}

Anonymous said...

udhaya u can't use loops u need to solve without the loop