Skip to content

Instantly share code, notes, and snippets.

@mbalayil
Created June 5, 2011 14:59
Show Gist options
  • Save mbalayil/1009025 to your computer and use it in GitHub Desktop.
Save mbalayil/1009025 to your computer and use it in GitHub Desktop.
C program to count the number of bits set in an unsigned integer(shift operator)
/**
* Shift operators shift the bits in an integer variable by a specified
* number of positions. The << operator shifts bits to the left, and the >>
* operator shifts bits to the right. The syntax for these binary operators
* is x << n and x >> n
* Each operator shifts the bits in x by n positions in the specified
* direction. For a right shift, zeros are placed in the n high-order bits
* of the variable; for a left shift, zeros are placed in the n low-order
* bits of the variable.
* Here are a few examples:
* Binary 00001000(decimal 8) right-shifted by 2 gives 00000010(decimal 2).
* Binary 00001000(decimal 8) left-shifted by 3 gives 01000000(decimal 64).
*
* One of the application of shift operation is to count the number of bits
* set in an unsigned integer.
* For example: f(0) = 0, f(1) = 1, f(2) = 1, f(3) = 2.
*
* More @ http://en.wikipedia.org/wiki/Bitwise_operation
**/
#include<stdio.h>
int main()
{
unsigned int i, b[32] = {0};
int j = 31, count = 0;
printf("\nEnter the unsigned integer:");
scanf("%d", &i);
while(i != 0)
{
// Bitwise AND operation b/w i & 0x00000001 is 1
// if the last bit of i is 1 and 0 if the last
// last bit is 0
b[j] = i & 0x00000001;
// Increment count whenever the bit is 1
if(b[j] == 1)
count++;
j--;
// Right shifting i by 1 to get the next bit
i = i >> 1;
}
printf("\nThe number of bits set in %d is %d", i, count);
// The array b gives the binary representation of i
printf("\nThe binary representation of %d is ", i);
for(i = j + 1; j < 32; j++)
printf("%d", b[j]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment