**Example:**

Input any number: 22

Output number of one's: 3 (in 4 byte integer representation)

Output number of zero's: 29 (in 4 byte integer representation)

### Required knowledge:

Basic C programming, Bitwise operator, If else, Loop### Logic:

You can easily count total number of zeros and ones in a given number if you know how to check if a bit is set or not. You simply need to iterate over each bits of the given number and check if the current bit is set then increment ones count otherwise increment zeros count.### Program:

/** * C program to count total number of zeros and ones in a binary number using bitwise operator */ #include <stdio.h> #define INT_SIZE sizeof(int) * 8 //Total number of bits in integer int main() { int num, temp, zeros, ones, i; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); temp = num; zeros = 0; ones = 0; for(i=0; i<INT_SIZE; i++) { //If LSB is set then increment ones otherwise increment zeros if(temp & 1) ones++; else zeros++; //Right shift bits of temp to one position temp >>= 1; } printf("Total number of zeros bits is %d (in %d byte integer representation)\n", zeros, sizeof(int)); printf("Total number of ones bits is %d (in %d byte integer representation)", ones, sizeof(int)); return 0; }

Output

Enter any number: 22

Total number of zeros bits is 29 (in 4 byte integer representation)

Total number of ones bits is 3 (in 4 byte integer representation)

Total number of zeros bits is 29 (in 4 byte integer representation)

Total number of ones bits is 3 (in 4 byte integer representation)

Happy coding ;)

### You may also like

- Bitwise operator programming exercises index.
- C program to convert decimal to binary number system using bitwise operator.
- C program to find one's complement of a binary number.
- C program to find two's complement of a binary number.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to flip bits of a binary number using bitwise operator.
- C program to swap two numbers using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.