Quote:
Originally Posted by quzah
??Code:char number[] = "11110000";
was that ment to replace int number[] = {1,1,1,1,0,0,0,0}; array ?
Printable View
Quote:
Originally Posted by quzah
??Code:char number[] = "11110000";
was that ment to replace int number[] = {1,1,1,1,0,0,0,0}; array ?
Don't tell me you don't know how to do some basic subtraction.
Quzah.
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.
Which is why we use subtraction...
Hint: - '0'
Quzah.
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.Quote:
Hint: - '0'
Faster and more elegant.Code:remainder = number%2; // == "remainder = number & 1"
Why? Use a loop. While you're at it put counting code into your loop and you would have solved your problem.Code:void binary(int number)
{
//... code ...
binary(number >> 1);
}
So, you don't got it? Dissect this bit of probably non-portable code:Quote:
Originally Posted by mburt
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;
}
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.Quote:
Originally Posted by laserlight
Quzah.
>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;
}