Monday, October 24, 2016

find hamming distance on bit level and charachtor level

1- script
import binascii
import re

# haming distance character level
def hamdistchar(str1, str2):
    diffs = 0
    for ch1, ch2 in zip(str1, str2):
        if ch1 != ch2:
            diffs += 1
    return diffs

# haming distance bit level, shift a bit from left to right until it reach 0 (example 11000 => 1000 => 000 ...)
def hamming1(x,y):
    assert len(x) == len(y)
    count,z = 0,int(x,2)^int(y,2)
    while z:
        if z&1:
            count += 1
        z >>= 1
    return count
# convert to bit string and find the character 1
def hamming3(x,y):
    assert len(x) == len(y)
    count,z = 0,int(x,2)^int(y,2)
    f = bin(z)
    return len(re.findall("1", f))

# remove the 1 character from right to left, until it become zero example (10111 => 1011 => 101 ...)
def hamming2(x,y):
    assert len(x) == len(y)
    count,z = 0,int(x,2)^int(y,2)
  
    while z:
        count += 1
        z &= z-1 # magic!
    return count  
      
text1 = "this is a test"
text2 = "wokka wokka!!!"
th = int(binascii.hexlify(text1), 16)
th2 = int(binascii.hexlify(text2), 16)

# print haming distance bit level
print hamming3(bin(th), bin(th2))

# print haming distance character level
print hamdistchar(text1, text2)

No comments:

Post a Comment