Counting the number of set bits in a number

Counting the number of set bits in a number


C++ : Counting the number of set bits in a number implemented in C++11

#include<iostream>
#include<bitset>
#include<cstdio>

using namespace std;

class Bits {
public:

    // Finding the number of set bits using bitset
    int CountSetBits(int num) {

        bitset<32> foo(num);
        cout << "Number : " << num << endl; 
        cout << "Binary representation : " << foo << endl; 
        cout << "Set bits using bitset : " << foo.count() << endl;
        cout << "Set bits using builtin_popcount : " << __builtin_popcount(num) << endl;
        /* Note : int __builtin_popcountl (unsigned long)
                  int __builtin_popcountll (unsigned long long) */
        return foo.count();
    }   
};

int main() {

    Bits b;
    b.CountSetBits(234);
    b.CountSetBits(512);
    b.CountSetBits(10);
    b.CountSetBits(65535);
    return 0;
}

Output showing the number of set bits in a number

Number : 234
Binary representation : 00000000000000000000000011101010
Set bits using bitset : 5
Set bits using builtin_popcount : 5
Number : 512
Binary representation : 00000000000000000000001000000000
Set bits using bitset : 1
Set bits using builtin_popcount : 1
Number : 10
Binary representation : 00000000000000000000000000001010
Set bits using bitset : 2
Set bits using builtin_popcount : 2
Number : 65535
Binary representation : 00000000000000001111111111111111
Set bits using bitset : 16
Set bits using builtin_popcount : 16

Copyright (c) 2020, Algotree.org.
All rights reserved.