# Thread: Help counting number of bits set in an integer

1. ## 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... 2. Code:
```while(i)
{
counter += i & 0x1;
i >> 1;
}``` 3. > 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. 4. Code:
` i >> 1;`
Code:
`i >>= 1;`
little typo vart 5. little typo vart
Thanks 6. Right shift on signed numbers is implementation-defined behaviour. Popular pages Recent additions 