Finding out no of 1's in a given no ??

How to find number of bit set in any given number ?

Say int x=7;
Number of 1's set in x are 3
In three steps:
1. Your number mod 2 to get the final bit's value.
2. Bit shift the whole number to throw away the last bit.
3. Repeat until 0.

In practice:
1
2
3
4
5
6
7
8
9
unsigned int bitcount(unsigned int val) {
    unsigned int count = 0;
    while (val != 0) {
        if (val % 2 == 1)
            ++count;
        val >>= 1;
    }
    return count;
}


EDIT:
On the other hand, you could store the number in a std::bitset and use the std::bitset::count method to get the number of 1s, if you wanted to.
Last edited on
Topic archived. No new replies allowed.