# binary comparation

Is there any function in c++ to convert decimal number to binary number without using divide algorithm? I want to count different bits of binary format of 2 numbers. like diff(0,2) is 1 bit. or diff(3,15) is 2 bit. I want to write diff function. thanks

## Answers

You can find the number of different bits by counting the bits in the xor of the two numbers. Something like this.

int count_bits(unsigned int n) { int result = 0; while(n) { result += 1; // Remove the lowest bit. n &= n - 1; } return result; } int diff(unsigned int a, unsigned int b) { return count_bits(a ^ b); }