Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C solved programs/examples on Bitwise Operators

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to count the number of bits to be flippe... >>
<< C program to swap two bits of a 32-bit integer num...