Using Xor to Determine Wether Number is Power of 2 Using C

By: Anuj

Level - Intermediate

Well if we have to determine wether a number is a power of 2 there can be tons of algorithm designed to do so using loops and conditional statements. But often there is constraint on program coded to perform under a certain complexity or efficiency.

You really dont want to waste your precious CPU processing for trivial task using giant loop or a switch statement or anything like it. Here i give you a better option, one unmatched in efficiency by any other algorithm which can do this task.

We use a mathematical concept that if we have to find wether X is a power of 2 then X ^ X-1 ( '^' Stands for XOR logic operation ) will return 0 value only when the X is a power of 2.

Now to demonstrate it using coding we will be creating a subroutine in the code below which take them number to be evaluated as input and will return 0 if number is a power of 2 and 0 otherwise.

Also we need to take case of special case in which number to evaluated is 0, which will also produce 0 as return value eventhough 0 is not a multiple of 2.

Source code below is written in C and is implementation of concept, how to determine the number is a power of 2.

#include
int ispowerof2 (int x) // Our Function{
if (!x || (x&(x-1)))
return 1;
else
return 0;
}

int main ()
{
int number;
printf ("nEnter A Number : ");
scanf ("%d", &number);

if (ispowerof2 (number))
{
printf ("nnNot a power of 2");
}
else
{
printf ("nnPower of 2");
}

return 0;

}

For More Articles like this see my personal blog

Top Searches on
Programming
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 
 • 

» More on Programming