Q:

C program to check whether all bits of a number are UNSET/LOW?

0

C program to check whether all bits of a number are UNSET/LOW?

Give a number of one byte (8 bits) and we have to check whether all bits are UNSET/LOW.

Example -1

Input number: 0 
Binary value: 00000000
Output: Yes, all bits are unset 

Example -2

Input number: 50 
Binary value: 00110011
Output: No, all bits are not unset 

To solved this program, we will use BITWISE AND (&) operator, we will traverse bits from 7 to 0 (in case of two bytes number, it would be 15 to 0 and so on...) and check if there is any SET/HIGH bit, then we will break the loop and output will be false that means "all bits are not UNSET/LOW".

All Answers

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

Consider the program:

#include <stdio.h>

//function to check whether all bits are 
//UNSET/LOW or not?
int isAllBitsUnset(unsigned int num)
{
    int loop, cnt=0;
    
    for(loop=7; loop>=0; loop--)
    {
        //check, if there is any SET/HIGH bit
        if( num & (1<<loop))
        {
            cnt =1;
            break;
        }
    }
    if(cnt==0)
        return 1; //true
    else
        return 0; //false
}

//main function
int main()
{
    unsigned int number;
    
    //read number
    printf("Enter an integer number (between 0-255): ");
    scanf("%d",&number);
    
    if(isAllBitsUnset(number))
        printf("All bits are UNSET/LOW.\n");
    else
        printf("All bits are not UNSET/LOW.\n");
        
    return 0;   
}

Output

First Run:

Enter an integer number (between 0-255): 0
All bits are UNSET/LOW.

Second Run:

Enter an integer number (between 0-255): 50
All bits are not UNSET/LOW.

We wrote a function int isAllBitsUnset(unsigned int num), it is taking an unsigned integer type number as an argument and returning 0 if all bits are not UNSET/LOW and 1 if all bits are UNSET/LOW.

function:

int isAllBitsUnset(unsigned int num)
{
    int loop, cnt=0;
    
    for(loop=7; loop>=0; loop--)
    {
        //check, if there is any SET/HIGH bit
        if( num & (1<<loop))
        {
            cnt =1;
            break;
        }
    }
    if(cnt==0)
        return 1; //true
    else
        return 0; //false
}

To check the bits, we are traversing loop from 7 to 0 (in case of 8 bits) and checking each bit, whether it is HIGH/SET or not, if any bit is HIGH/SET then value of cnt will be 1 (which is 0 initially, cnt is using as a flag variable) and loop will break.

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 swap two bits of a byte... >>
<< C program to swap two words/bytes....