Hello,
Does anyone know how to count the number of 1's and 0's in a binary sequence.
This is a discussion on Binary Sequence within the C++ Programming forums, part of the General Programming Boards category; Hello, Does anyone know how to count the number of 1's and 0's in a binary sequence....
Hello,
Does anyone know how to count the number of 1's and 0's in a binary sequence.
You can put it in a bitset and use the count member function
If it happens to already be in a string/character-array form you could also use the STL count_if function.
I used to be an adventurer like you... then I took an arrow to the knee.
or just the std::count() see last example:Originally Posted by hk_mp5kpdw
Code:#include <bitset> #include <string> #include <iostream> #include <algorithm> const unsigned number = 15122; int countBits(unsigned n) { unsigned count = 0; while(n) { if (n&1)count++; n = n>>1; } return count; } int main() { std::string str = std::bitset<32>(number).to_string(); std::cout << countBits(number) << "\n"; std::cout << std::bitset<32>(number).count() << "\n"; std::cout << std::count(str.begin(), str.end(),'1')<< "\n"; }