You are on page 1of 4

HAMMING CODE

EX:NO:1
Aim:
To correct the error in the data using Error correction technique.

Sender side code:

def calcParityBits(array, n):

l = len(array)

for i in range(n):

value = 0

for j in range(1, l + 1):

if(j & (2**i) == (2**i)):

value = value ^ int(array[-1 * j])

array = array[:l-(2**i)] + str(value) + array[l-(2**i)+1:]

return array

d = input("Enter the input bit\n ")

s = len(d)

for n1 in range(s):

if(2**n1 >= s + n1 + 1):

break

n =n1

print("\n")

print(n)

j=0

m=1
s = len(d)

r = ''

for i in range(1,s+n+1 ):

if(i == 2**j):

r = r + '0'

j += 1

else:

r = r + d[-1 * m]

m += 1

array = r[::-1]

array = calcParityBits(array, n)

print("\nBit at the sender end is " + array)

file=open("3.txt","w")

file.write(array)

file.close()

Receiver side code:

import random

def detectError(arr, nr):

n = len(arr)

res = 0

for i in range(nr):

val = 0

for j in range(1, n + 1):

if(j & (2**i) == (2**i)):

val = val ^ int(arr[-1 * j])


res = res + val*(10**i)

return int(str(res), 2)

file=open("3.txt","r")

arr=file.read()

r=len(arr)

j=0

dummy=random.randint(1,6)

if dummy%2!=0:

arr1=''

x='1248'

dummy=int(random.choice(x))

'''print(arr)'''

'''arr = '11101001110'

print("Error Data is \n " + arr)'''

for i in arr:

if j==dummy and i=='1':

arr1+='0'

if j==dummy and i=='0':

arr1+='1'

if j!=dummy:

arr1+=i

j+=1

print(len(arr1))

print("Data at the receiver end is \n"+arr1)

correction = detectError(arr1, r)

print("\nError at which position \n" + str(int((correction))))

else:
print("Data at the receiver end is : \n"+arr)

correction = detectError(arr, r)

print("\nError at which position \n" + str(correction))

Sender Output:

Intermediate file:

Receiver Output:

You might also like