How to check whether all bits of a number are unset in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

int isAllBitsUnset(unsigned int num) {
    while (num > 0) {
        if ( (num & 1) == 1) {
            return false;
        }
        num = num >> 1;
    }
 
    return true;
}

int main()
{
    unsigned int num = 28; // 00011100
 
    if (isAllBitsUnset(num)) {
        printf("All bits are unset\n");
    }
    else {
        printf("Not all bits are not unset\n");
    }
    
    num = 0; // 00000000
 
    if (isAllBitsUnset(num)) {
        printf("All bits are unset");
    }
    else {
        printf("Not all bits are not unset");
    }
        
    return 0;   
}
  
  
  
  
/*
run:
  
Not all bits are not unset
All bits are unset
  
*/

 



answered Dec 20, 2023 by avibootz
...