To find the bits that are different, you need to XOR
the values:
unsigned int first = 22;
unsigned int second = 15;
unsigned int result = first ^ second; // only the bits that are different
// will be set to 1 in result
To count the 1-bits in result
you can use:
unsigned int CountBits(unsigned int n) {
unsigned int count = 0;
while(n) {
count += n & 0x01; // checks the least significant bit of n
// if the bit is 1, count is incremented
n >>= 1; // shift all bits of n one to the right
// if no 1 bits are left, n becomes 0 and the loop ends
}
return count;
}
unsigned int count = CountBits(result);
To do it in one step:
unsigned int count = CountBits(first ^ second);
On some systems, the POPCNT
instruction could be used instead.
Update - Full example:
#include <stdio.h>
unsigned int CountBits(unsigned int n) {
unsigned int count = 0;
while(n) {
count += n & 0x01;
n >>= 1;
}
return count;
}
int main(void) {
unsigned int first = 22;
unsigned int second = 15;
unsigned int result = first ^ second;
unsigned int count = CountBits(result);
printf("result: %u - count: %u\n", result, count);
return 0;
}
Prints:
result: 25 - count: 3
Or, with an extra function:
#include <stdio.h>
unsigned int CountBits(unsigned int n) {
unsigned int count = 0;
while(n) {
count += n & 0x01;
n >>= 1;
}
return count;
}
unsigned int CountDifferentBits(unsigned int n1, unsigned int n2) {
return CountBits(n1 ^ n2);
}
int main(void) {
unsigned int count = CountDifferentBits(22, 15);
printf("Different bits count: %u\n", count);
return 0;
}