Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

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

$
0
0
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 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
X
_
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)

Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles