Q:

Write a program to check an integer is a power of 2?

0

Write a program to check an integer is a power of 2?

All Answers

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

Here, I am writing a small algorithm to check the power of 2. If a number is a power of 2, the flag will be 1.

#include <stdio.h>
int main()
{
    int flag = 0;
    int data = 0;
    printf("Enter the number ");
    scanf("%d",&data); //Get the number
    flag = ((data != 0) && !(data & (data - 1))); // check the power of 2
    if(flag == 1)
    {
        printf("Number is a power of 2 \n");
    }
    else
    {
        printf("Enter number is not power of 2 \n");
    }
    return 0;
}

Note: Here I assume that bit of register starts with 0th position, it means the 2nd position is actually 3rd bits.

D7 D6 D5 D4 D3 D2 D1 D0

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

total answers (1)

How to set a particular bit in C?... >>
<< Detect if two integers have opposite signs?...