Quick Method Using Xor To Determine Whether Number Is Power Of 2 Using C
Quick Method Using Xor To Determine Whether Number Is Power Of 2 Using C
By Anuj Pathania
Level – Intermediate
Well if we have to determine whether 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 don t 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 whether 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 even though 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 www.cencyclopedia.com
A Pro C Programmer
Article Source: http://EzineArticles.com/?expert=Anuj_Pathania
http://EzineArticles.com/?Quick-Method-Using-Xor-To-Determine-Whether-Number-Is-Power-Of-2-Using-C&id=653912
Related post
Internet Security Software Review – 4 Quick Tips
...
World of Warcraft Power Levelling Guide-What You Need To Know!
...
The Right Way To Discharge Capacitor In Switch Mode Power Supplies
...
History of the Computer – Memory Error Correction Codes Part 2 of 2
...
Professional vs Consumer Video Card Solutions
...