C program to check a given number is the power of 2 using bitwise operator

Here, we are going to learn how to check a given number is the power of 2 using bitwise operator in C programming language?
Submitted by Nidhi, on July 31, 2021

Problem Solution:

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.

C Bitwise Operators Programs »



Related Programs



Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.