Read an integer number, and check whether the input number is a power of 2 or not using bitwise operator.

Program:

The source code to check a given number is the power of 2 using bitwise operator is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check a given number is power of 2
// using bitwise operator
#include <stdio.h>
int checkPowerOf2(unsigned int num)
{
// Check if the number has only one set bit
if ((num & (num - 1)) != 0)
return 0;
return 1;
}
int main()
{
unsigned int num = 0;
printf("Enter Number: ");
scanf("%d", &num);
if (checkPowerOf2(num))
printf("Given number is power of 2.\n");
else
printf("Given number is not power of 2.\n");
return 0;
}

Output:

RUN 1:
Enter Number: 32
Given number is power of 2.
RUN2:
Enter Number: 2048
Given number is power of 2.
RUN 3:
Enter Number: 524
Given number is not power of 2.

Explanation:

In the above program, we created two functions checkPowerOf2() and main(). The checkPowerOf2() function is used to check given integer number is a power of 2 or not.

In the main() function, we read an integer number from the user and called the checkPowerOf2() function to check the given number is a power of 2 or not and printed the appropriate message on the console screen.

Read an integer number, and check whether the input number is a power of 2 or not using bitwise operator.

Program:The source code to check a given number is the power of 2 using bitwise operator is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

Output:Explanation:In the above program, we created two functions

checkPowerOf2()andmain(). ThecheckPowerOf2()function is used to check given integer number is a power of 2 or not.In the

need an explanation for this answer? contact us directly to get an explanation for this answermain()function, we read an integer number from the user and called thecheckPowerOf2()function to check the given number is a power of 2 or not and printed the appropriate message on the console screen.