The Hamming distance defines the number of bits that need to change in a binary value in order to produce another value.
Hamming distance |
Coding
The following uses a simple bit-shift operation and X-OR to implement the method, along with the import of a library (commpy) in order to check the answer:
import sys import commpy from bitstring import BitArray if (len(sys.argv)>1): val1=sys.argv[1] if (len(sys.argv)>1): val2=sys.argv[2] def hamming2(str1, str2): if len(str1) <> len(str2): print "Strings differ is size" return 0 a = int(str1, 2) b = int(str2, 2) count= 0 c = a ^ b while c: count += 1 c &= c - 1 return count print "Binary form:\t",val1," - ",val2 print "Decimal form:\t",int(val1,2)," - ",int(val2,2) print "" print "Hamming distance is ",hamming2(val1,val2) v1=BitArray(bin=val1) v2=BitArray(bin=val2) print "Hamming distance is ",commpy.utilities.hamming_dist(v1,v2)