Check out example codes for "bitwise count total set bits". It will help you in understanding the concepts better.

Code Example 1

// C++ program to demonstrate __builtin_popcount() 
#include <iostream> 
using namespace std; 
  
int main() 
{ 
    cout << __builtin_popcount(4) << endl; 
    cout << __builtin_popcount(15); 
  
    return 0; 
}

Code Example 2

countBits = (n) => n.toString(2).split("0").join("").length;

Code Example 3

//WAP to find setbits (total 1's in binary ex. n= 5 => 101 => 2 setbits
int count{}, num{};
  cin >> num;

  while (num > 0) {
    count = count + (num & 1); // num&1 => it gives either 0 or 1
    num = num >> 1;	// bitwise rightshift 
  }

	 cout << count; //count is our total setbits

Learn ReactJs, React Native from akashmittal.com