Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two binary numbers and get the different bits [duplicate]

Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?

I want to write a program to get the number of 1's bit in comparing two numbers.if I compare the bits between any two numbers to find where the binary numbers are different in the 1's and 0's. in other words Exclusive OR (XOR) relationship.

like if 22 (which has 10110 binary)and compare it with 15 (which has 01111 binary)

the first one 10110

the second one 01111

the result 11001

and the answer would be 25 but what I want to get is 3 where there is three 1's and 0's that are different.

like image 481
TTT Avatar asked Mar 31 '12 09:03

TTT


People also ask

How do you find the difference in bits?

Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y. For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers).

Which gate can be used for comparing two binary number?

2-Bit Magnitude Comparator: A comparator used to compare two binary numbers each of two bits is called a 2-bit Magnitude comparator. It consists of four inputs and three outputs to generate less than, equal to, and greater than between two binary numbers.

How can I compare two bits in C++?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.


2 Answers

Hrmmm, the first non-recursive idea that comes to mind is:

int a = ...;
int b = ...;
int x = a ^ b;

int count;

for (int i = 0; i < 32; ++i) {
    if (x & (1 << i)) {
        ++count;
    }
}
like image 167
Corbin Avatar answered Sep 22 '22 12:09

Corbin


std::bitset::count should do what you're looking for:

http://www.cplusplus.com/reference/stl/bitset/count/

http://en.cppreference.com/w/cpp/utility/bitset/count

like image 43
Ben Cottrell Avatar answered Sep 18 '22 12:09

Ben Cottrell