C Programming Code Examples C > Bitwise Operators Code Examples program to count zeros and ones in a binary number program to count zeros and ones in a binary number Write a C program to input a number from user and count total number of ones (1s) and zeros (0s) in the given number using bitwise operator. How to count zeros and ones in a binary number using bitwise operator in C programming. Input a number from user. Store it in some variable say j. Compute total bits required to store integer in memory i.e. INT_SIZE = sizeof(int) * 8. Initialize two variables to store zeros and ones count, say zeros = 0 and ones = 0. Run a loop from 0 to INT_SIZE. The loop structure should look like for(i=0; i<INT_SIZE; i++). Inside the loop check if Least Significant Bit of a number is set, then increment ones by 1 otherwise increment zeros by 1. Right shift j 1 time i.e. perform j = j >> 1;. /* C program to count total 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 j, zeros, ones, i; /* Input number from user */ printf("Enter any number: "); scanf("%d", &j); zeros = 0; ones = 0; for(i=0; i<INT_SIZE; i++) { /* If LSB is set then increment ones otherwise zeros */ if(j & 1) ones++; else zeros++; /* Right shift bits of j to one position */ j >>= 1; } printf("Total zero bit is %d\n", zeros); printf("Total one bit is %d", ones); return 0; }