Saturday 11 November 2017

C Program to Count Number of bits set to 0 in an Integer


Code:

#include stdio.h
#define NUM_BITS_INT (8*sizeof(int))

int count_unset(int);

int main()
{
    int i, num, snum, res, count = 0;

    printf("\nEnter the number");
    scanf("%d", &num);
    /*
     * Check each bit whether the bit is set or unset
     * Uses >> and & operator for checking individual bits
     */
    for (i = 0;i <= NUM_BITS_INT;i++)
    {
        snum = num >> i;
        res = snum & 1;
        if (res == 0)
            count++;
    }
    printf("%d", count);
}

Output:

Enter the number - 128
31
$ a.out
Enter the number -127
6


More C programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...