This is a C Program to check if a given integer is power of 2 using bitwise operators.

This C Program checks if a given integer is power of 2 using bitwise operators.

Take input from the user and performs bitwise operations as shown in the program below.

Here is source code of the C Program to check if a given integer is power of 2 using bitwise operators. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C Program to Check if a given Integer is Power of 2 using Bitwise Operators */ #include <stdio.h> #define NUM_BITS_INT (8*sizeof(int)) int power_of_2(unsigned int); int main() { unsigned int num; printf("\nEnter Number"); scanf("%d", &num); power_of_2(num); } /* * Finding the power of 2 using bit wise operators */ int power_of_2(unsigned int x) { int i, count = 0, result, shift_num; for (i = 0;i <= NUM_BITS_INT;i++) { shift_num = x >> i; result = shift_num & 1; if (result == 1) count++; } /* *If number of bits set to 1 are odd then the number is power of 2 *If number of bits set to 0 are even then the number is not power of 2 */ if (count % 2 == 1) printf("YES"); else printf("NO"); }

In this C Program, we are reading the number using ‘num’ variable. The power_of_2() function is used for finding the power of 2 using bit wise operators. Binary Right Shift operator the left operands value is moved right by the number of bits specified by the right operands and assign the value to ‘shift_num’ variable.

The ‘result’ variable is used compute the Binary AND operation by copying a bit to the result if it exists in both operands. If condition statement is used to check the value of ‘res’ variable is equal to 1. If the condition is true then execute the statement and increment the value of ‘count’ variable.

If else condition statement is used to check that the number of bits set to 1 is odd and print the number is power of 2. Otherwise, if the condition is false and print the number is not power of 2 and displays the output of the program.

$ gcc bit25.c $ a.out Enter Number128 YES $ a.out Enter Number126 NO

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

**Next Steps:**

- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Buy Computer Science Books