C Program to find whether given number is power of 2 or not using Bitwise operators !

Example:

Given: num = 64. 2 power 7 is 64, hence 64 is power of 2.

num = 5. This is not a power of 2.

Logic:
1. Take a number num.
2. Perform AND operation between num and num -1(num & num -1).
3. If it is zero then the number is power of 2, Else if it is non-zero then number is not power of 2.

Source code:

 

#include<stdio.h>
int power(int );
int main()
{
      int num, res;
      printf("enter a num\n");
      scanf("%d",&num);
      res = power( num );
      if(!res)
            printf("number %d is power of 2\n",num);
      else
            printf("number %d is not power of 2\n",num);
}
int power(int num)
{
      return num & (num-1);
}

This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

We offer Embedded System certification courses in Bangalore ! 

One Response Comment

  • Amritesh  September 24, 2016 at 8:23 am

    Thanks a lot sir, nice program for beginners.

    Reply

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.