# Thread: counting 1's in a binary byte

1. Originally Posted by quzah
I'd suggest getting a better C++ book. Haven't heard of string literals yet I guess huh?
Code:
`char number[] = "11110000";`

Quzah.

Code:
`char number[] = "11110000";`
??
was that ment to replace int number[] = {1,1,1,1,0,0,0,0}; array ?

2. Don't tell me you don't know how to do some basic subtraction.

Quzah.

3. No need for subtraction with such a null terminated string, but from the initial post it looks like the input is supposed to be some integer, not a string containing a representation of an integer in binary.

4. Which is why we use subtraction...

Hint: - '0'

Quzah.

5. Hint: - '0'
That is going to be rather redundant, in my opinion (as I stated in my previous post). One can simply count the '1' chars directly from the null terminated string. On the other hand, if you are provided with an integer, such subtraction will not work, since we cannot subtract a char from a string.

6. Code:
`	remainder = number%2; // == "remainder = number & 1"`
Faster and more elegant.

Code:
```void binary(int number)
{
//... code ...
binary(number >> 1);
}```
Why? Use a loop. While you're at it put counting code into your loop and you would have solved your problem.

7. Originally Posted by mburt
Got it. The only downside is that you have to store the binary number in an array.
So, you don't got it? Dissect this bit of probably non-portable code:
Code:
```#include <iostream>
#include <string>

long binaryCount(long number)
{
number = (number & 0x55555555) + ((number & 0xaaaaaaaa) >> 1);
number = (number & 0x33333333) + ((number & 0xcccccccc) >> 2);
number = (number & 0x0f0f0f0f) + ((number & 0xf0f0f0f0) >> 4);
number = (number & 0x00ff00ff) + ((number & 0xff00ff00) >> 8);
return   (number & 0x0000ffff) + ((number & 0xffff0000) >> 16);
}

int main()
{
std::string input = "Awesome";

long finalCount = 0;
for(int i = 0; input[i]; i++)
finalCount += binaryCount(input[i]);

std::cout << finalCount << std::endl;

return 0;
}```

8. Originally Posted by laserlight
That is going to be rather redundant, in my opinion (as I stated in my previous post). One can simply count the '1' chars directly from the null terminated string. On the other hand, if you are provided with an integer, such subtraction will not work, since we cannot subtract a char from a string.
Sure it's redundant. He didn't ask for the best solution, Dave's already posted a link to those. He asked how to initialize it without putting , between them. Asked. Answered.

Quzah.

9. >im trying to figure out how to count the 1's in the binary bytes outputted.
Code:
```#include <bitset>
.
.
for ( int i=0; i<(int)name.size(); i++ )
{
cout << "1's in " << name[i] << ": " << std::bitset<8>(name[i]).count() << endl;
}```

Popular pages Recent additions