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

Example

Input

Input any number: 22

Output

Output number of ones: 3
Output number of zeros: 29

Required knowledge

Bitwise operators, Data types, Variables and Expressions, Basic input/output, If else, For loop

Logic to count zeros and ones in a binary number

Step by step descriptive logic to count zeros and ones in a binary number.

  1. Input a number from user. Store it in some variable say num.
  2. Compute total bits required to store integer in memory i.e. INT_SIZE = sizeof(int) * 8.

    Must read – How to find size of a data type using sizeof() operator.

  3. Initialize two variables to store zeros and ones count, say zeros = 0 and ones = 0.
  4. Run a loop from 0 to INT_SIZE. The loop structure should look like for(i=0; i<INT_SIZE; i++).
  5. Inside the loop check if Least Significant Bit of a number is set, then increment ones by 1 otherwise increment zeros by 1.
  6. Right shift num 1 time i.e. perform num = num >> 1;.

Program to count zeros and ones in a binary number

/**
 * 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 num, zeros, ones, i;

    /* Input number from user */
    printf("Enter any number: ");
    scanf("%d", &num);

    zeros = 0;
    ones = 0;

    for(i=0; i<INT_SIZE; i++)
    {
        /* If LSB is set then increment ones otherwise zeros */
        if(num & 1)
            ones++;
        else
            zeros++;

        /* Right shift bits of num to one position */
        num >>= 1;
    }

    printf("Total zero bit is %d\n", zeros);
    printf("Total one bit is %d", ones);

    return 0;
}

In the above code if(num & 1) is equivalent to if((num & 1) == 1).
In the statement num >>= 1; I have used shorthand assignment operator which is equivalent to num = num >> 1;

Output

Enter any number: 22
Total zero bit is 29
Total one bit is 3

Happy coding 😉