This program is for counting the number of bit set and unset.
Run through each bit and increment the set count if the bit is set else increment the unset counter.
#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)
int display_binary(unsigned int num)
{
int i;
for(i= MAX_BIT-1;i>=0;i--)
{
if((num >> i)&1)
printf("1");
else
printf("0");
}
}
int main()
{
unsigned int num;
int set = 0;
int unset = 0;
int i= 0;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n The number in decimal is:");
display_binary(num);
for (i; i < MAX_BIT; i ++)
{
if ((num >> i) & 1)
set++;
else
unset++;
}
printf("\n No of bit set: %d and unset: %d\n", set, unset);
return 0;
}
Output:
Enter the number: 12
The number in decimal is:00000000000000000000000000001100
No of bit set: 2 and unset: 30
Categories: C Language
Leave a Reply