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

 By: Anuj
 Level - IntermediateWell 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
Programming
 • Get Free Information About Custom Software Development • Digital Art: Explore Illustration • A Must-have Real Estate Software for Realty Business • Perl Makes Life Easier • Desktop Applications Vs. Web Applications • net Application Development • Crop Image File Size, Width & Height Using Php Script • Certification Basics • What are Certification Braindumps? • Understanding ASP.NET Validation Controls • The Top Ten Reasons for Learning Linux, Number 6, Linux and Php • Web Hosting Technology for Php • A Time-Saving Programming Tactic That Doesnt Work • Visual Basic .net Programming • Free Java Script Tutorial • Server Side PHP Classified Ads Software • Is Software Hard? • Web Design Myths • Finding Hidden Characters in a File • Ccna Testing Centers: What to Expect (info Includes All Exams) » More on Most Popular Programming Articles