Q:

Write a program to count set bits in an integer?

0

Write a program to count set bits in an integer?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

There are a lot of ways to count the number of bits in a given integer, here I am writing two approaches naive and  Brian Kernighan’s.

In naive approach requires one iteration per bit until no more bits are set.

#include <stdio.h>
#define CHAR_BITS  8  // size of character
#define INT_BITS  ( sizeof(int) * CHAR_BITS)
int main()
{
    unsigned int CountSetBits = 0; //Total number of bit set.
    unsigned int n = 0; //Variable that set bits you want to count
    printf("Enter the Number ");
    scanf("%d", &n);
    while (n)
    {
        CountSetBits += n & 1;
        n >>= 1;
    }
    printf("Number of 1 = %d", CountSetBits);
}

Brian Kernighan’s method goes through as many iterations as there are set bits.

1. Initialize CountSetBits = 0

2. If integer n is not zero.

( a ). Perform bitwise operation and assign the value back to the n.
These bitwise operations clear the least significant.
n &= (n – 1);

( b ). Increment CountSetBits by 1.

( c ). Again go to step 2.

3. If there are no set bits remaining then return CountSetBits.

#include <stdio.h>
#define CHAR_BITS  8  // size of character
#define INT_BITS  ( sizeof(int) * CHAR_BITS)
int main()
{
    unsigned int n = 0; //Variable that set bits you want to count
    unsigned int CountSetBits = 0; //Total number of bit set
    printf("Enter the Number ");
    scanf("%d", &n);
    while(n)
    {
        n &= (n - 1); // clear the least significant bit set
        CountSetBits++;
    }
    printf("Number of 1 = %d", CountSetBits);
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rotate bits of a number in C?... >>
<< Write an Efficient C Program to Reverse Bits of a ...