Feb 5, 2014 at 7:32am UTC
I'm working on creating this, however, my program gives me a weird integer binary value when counting the occurrences. For example, when a decimal is entered, it outputs a bunch of random numbers instead of counting the occurrence.
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <iostream>
#include <string>
using namespace std;
unsigned count_bit_matches( unsigned long value, unsigned long pattern )
{
unsigned result = 0;
unsigned long mask = 1;
for (unsigned long p = pattern; p; p >>= 1)
mask <<= 1;
mask != 1;
while (value)
{
result += ((value & mask) == pattern);
value >>= 1;
}
return result;
}
string to_binary( unsigned long n )
{
string result;
while (n)
{
result = (char )((n & 1) + '0' ) + result;
n >>= 1;
}
return result.empty() ? string("0" ) : result;
}
void test( unsigned value, unsigned pattern )
{
cout << value << ": '" << to_binary( value )
<< "', " << count_bit_matches( value, pattern )
<< " groups of '" << to_binary( pattern ) << "'.\n" ;
}
int main()
{
test( 183, 3 );
test( 183, 7 );
test( 183, 5 );
test( 183, 2 );
test( 183, 4 );
return 0;
}
Thanks.
EDIT: Nevermind, simple mistake, mask != 1 should have been mask -= 1.
Last edited on Feb 23, 2014 at 3:47am UTC
Feb 5, 2014 at 7:49am UTC
Solved.
Last edited on Feb 23, 2014 at 3:47am UTC
Feb 5, 2014 at 11:25am UTC
Solved.
Last edited on Feb 6, 2014 at 5:33pm UTC