[ Log On ]
  • Home
  • Tst
  • Cha
  • Enc
  • Code
  • IP
  • Fun
  • Sub
  • DigF
  • Cis
  • Com
  • Db
  • About
  • Netsim

Hamming distance

 

Back The Hamming distance defines the number of bits that need to change in a binary value in order to produce another value.

Hamming

Enter binary values (the page should detect binary or decimal values):

Bit value 1:
Bit value 2:

Binary input: Decimal input:

Try an example

  • Distance between 111 and 101 gives a Hamming distance of 3. Calc
  • Distance between 10101010 and 011111111 gives a Hamming distance of 5. Calc

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)