×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

Learn: how we can check that whether all bits of a one byte (8 bits) number are UNSET/LOW using C program? Here, we are implemented the program for this using Bitwise AND (&) operator.

Problem statement

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 

Checking whether all bits of a number are UNSET/LOW

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".

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

#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.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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