counting 1's in a binary byte
basically i need to know how to count the 1's in example: 10110001
then output : 4 (for this example)
here is my code.. im trying to figure out how to count the 1's in the binary bytes outputted. Im thinking i may have to add a if statement that if bit = 1, add a count ??? help please :) thanks
Code:
#include <cstdlib>
#include <iostream>
using namespace std;
void binary(int);
int main()
{
string name = "";
cout<< "Please enter your name: ";
cin >> name;
for ( int i=0; i<(int)name.size(); i++ )
{
cout<< '\n' ;
binary((int)name[i]);
cout <<" ";
}
cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void binary(int number)
{
int remainder;
if(number <= 1)
{
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;
}