Get number of 1s in a set of binary numbers
-
is there a functions of method where I can obtain the number of 1s in a set of binary numbers? eg. I have data = 59; //00111011; and I get nCount = 5; // since there are 5 ones in the binary equivalent of 59 Thanks in advance.
This should do what you want. int GetHighBitCount(int i) { int iResult=0; while (i) { // Mask for least significant bit of 'i' if (i & 0x00000001) iResult++; // Right shift 'i' by one bit i >>= 1; } return iResult; } Mark Jones Software Engineer Hampshire UK
-
is there a functions of method where I can obtain the number of 1s in a set of binary numbers? eg. I have data = 59; //00111011; and I get nCount = 5; // since there are 5 ones in the binary equivalent of 59 Thanks in advance.
#include <iostream>
#include <bitset>int main(int argc, char* argv[])
{
unsigned long data = 59;
int nCount = std::bitset<32>(data).count();std::cout << nCount << endl; return 0;
}
This asssumes 32 bit longs, I don't remember the correct way to portably get the number of bits in a type.