# Help counting number of bits set in an integer

• 12-07-2006
JayDiddums10
Help counting number of bits set in an integer
I have to write a program that counts the number of bits set in an integer. For example, the number 5 (decimal), which is 0000000000000101 (binary), has two bits set. I know how to count the number of bits in a char, but I don't know how to count the extra 8 bits in an integer. How would i navigate to the other byte and count the eight bits?

Here is how i'd count the number of bits in a char...

Code:

``` #include <stdio.h> void main() {         char ch = 5;  /*assign it a random number*/         int counter = 0;         int i;                 for (i = 0x80; i > 0; i = (i >> 1))  {             if ((ch & i) != 0)                 ++counter;         } }```
Thanks for any help with this...
• 12-07-2006
vart
Code:

```while(i) {   counter += i & 0x1;   i >> 1; }```
• 12-07-2006
Salem
> void main()
main returns an int

> How would i navigate to the other byte and count the eight bits?
Other 8 ?
The size of an int varies from machine to machine, as do all the other types.

If you include limits.h, then the number of bits in an int is
CHAR_BIT * sizeof(int)

> for (i = 0x80;
Well the easy thing to do is start with a different constant which starts with the most significant bit of the int.

Hint
unsigned int allOnes = ~0;
Using that and some bit operations, you should be able to find the value of the most significant bit in an int without explicitly saying it in your code.
• 12-07-2006
sl4nted
Code:

` i >> 1;`
Code:

`i >>= 1;`
little typo vart
• 12-07-2006
vart
Quote:

little typo vart
Thanks
• 12-07-2006
Salem
Right shift on signed numbers is implementation-defined behaviour.