C program to count number of 1’s and 0’s in a binary number

Write a C program to input any number from user and count total number of one's (1's) and zero's (0's) in the given number (in binary representation) using bitwise operator. How to count total number of ones and zeros in a binary number using bitwise operator in C programming.

Example

Input

Input any number: 22

Output

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

Program to count total 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, temp, zeros, ones, i;

    // Input 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 zero bit is %d (in %d byte integer representation)\n", zeros, sizeof(int));
    printf("Total one bit is %d (in %d byte integer representation)", ones, sizeof(int));

    return 0;
}

Output

Enter any number: 22
Total zero bit is 29 (in 4 byte integer representation)
Total one bit is 3 (in 4 byte integer representation)

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>