How to count the number of zero bits in a number with C++

1 Answer

0 votes
#include <iostream>

int countZeroBits(int num, int totalBits) {
    int count = 0;
 
    for (int i = 0; i < totalBits; i++) {
        if ((num & (1 << i)) == 0) {
            count++;
        }
    }
 
    return count;
}
 
int main() {
    int num = 453; // 0000 0001 1100 0101
 
    int zeroBits = countZeroBits(num, 16);
     
    std::cout << "Number of zero bits: " << zeroBits << "\n";
}
 
 
 
/*
run:
    
Number of zero bits: 11
             
*/

 



answered Oct 25, 2024 by avibootz

Related questions

1 answer 98 views
1 answer 193 views
1 answer 189 views
1 answer 219 views
...