mansi
mansi

Reputation: 877

How to calculate hamming distance of number having binary format

I tried below code for calculating hamming distance of two decimal numbers, and got the expected result:

 SELECT BIT_COUNT('16056695327593349911' ^ '13147651924325057303') AS hamming_distance ;    

output : 8

But when I tried converting above two decimal numbers to binary, it gives me a wrong result:

I tried below query:

 SELECT BIT_COUNT(CAST(CONV('16056695327593349911',10,2) AS UNSIGNED INTEGER) ^ CAST(CONV('13147651924325057303',10,2) AS UNSIGNED INTEGER)) AS hamming_distance ; 

 output: 0   

I want to calculate hamming distance of two binary numbers.

Upvotes: 1

Views: 636

Answers (1)

axiac
axiac

Reputation: 72396

There is no such thing as "binary number" or "decimal number". A number is a quantity. Ten items are ten items, no matter if you write their number as 10 (base 10), 1010 (base 2), 'X' (roman numerals) or 'ten' (English). The number is still the same, only the way we write it differs.

The bitwise XOR operator doesn't care how do you write the numbers, it internally represents them in binary and applies the XOR operation on their bits.

This is how the numbers you posted (16056695327593349911 and 13147651924325057303) look in binary:

1101111011010100110101110101010000010011111000000100000000000000
1011011001110101110101111100010000010011111000000100000000000000
 ^^ ^   ^ ^    ^        ^  ^

I marked under them the 8 positions where they differ in their binary representation. This number (8) is the Hamming distance you compute.

The value of 16056695327593349911 ^ 13147651924325057303 is 7539307869670211584 and its binary representation is below:

0110100010100001000000001001000000000000000000000000000000000000
 ^^ ^   ^ ^    ^        ^  ^

Please note that it has 1 on the positions marked on the first figure (where the input numbers have different bits in their binary representation) and 0 where the corresponding bits of the input numbers are equal.


The Hamming distance of two strings is the number of positions where they differ. If you use the bitwise XOR operator to find the differences then you are technically computing the Hamming distance of the binary representations of the two input numbers.

Upvotes: 1

Related Questions