How to Check Wether Number is Power of 2 or Not in C

It is very much easy to check the power of 2.  If you observe the pattern for the different numbers.



For example: 

3 = 11
4 = 100

7  = 111

8 = 1000

15 = 1111

16 = 10000

31 = 11111

32 = 100000

Observe that both numbers carefully. You can see if you do anding of both the numbers then result will be zero. 

Example 3 & 4 = 0.

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int chPow2 = 30;
    if((chPow2 & (chPow2 - 1)) == 0)
        printf("Number: %d is power of 2", chPow2);
    else
        printf("Number: %d is not power of 2", chPow2);

    getch();

    return 0;
}


Related Post:


Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault ?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...