2020-05-30 04:23:24 +08:00
|
|
|
int hammingDistance(int x, int y)
|
|
|
|
{
|
|
|
|
int difference =
|
2020-06-28 23:25:37 +08:00
|
|
|
x ^ y; // The XOR operator generates the bitwise difference in the
|
|
|
|
// binary representation of two numbers If bit in ith position
|
|
|
|
// of both numbers is same, bit in difference is 0, otherwise 1
|
|
|
|
int TotalBits = sizeof(difference) * 8; // total number of bits
|
2019-10-12 18:10:42 +08:00
|
|
|
int i, distance = 0;
|
2020-05-30 04:23:24 +08:00
|
|
|
for (i = 0; i < TotalBits; i++)
|
|
|
|
{
|
|
|
|
if (difference &
|
|
|
|
(UINT32_C(1)
|
2020-06-28 23:25:37 +08:00
|
|
|
<< i)) // if the bit on the ith position of 32 bit input is 1,
|
|
|
|
// then proceed Further note the use of UINT32_C to convert
|
|
|
|
// 1 to unsigned 32 bit int, as just 1 is treated as int
|
|
|
|
// which cannot be shifted left more than 30 times
|
2019-10-12 18:10:42 +08:00
|
|
|
distance += 1;
|
2020-05-30 04:23:24 +08:00
|
|
|
}
|
2019-10-12 18:10:42 +08:00
|
|
|
return distance;
|
|
|
|
}
|