-
Notifications
You must be signed in to change notification settings - Fork 9
/
hamming.py
100 lines (76 loc) · 2.43 KB
/
hamming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
option=int(input('Press 1 for generating hamming code \nPress 2 for finding error in hamming code\n\t Enter your choice:--\n'))
if(option==1): # GENERATE HAMMING CODE
print('Enter the data bits')
d=input()
data=list(d)
data.reverse()
c,ch,j,r,h=0,0,0,0,[]
while ((len(d)+r+1)>(pow(2,r))):
r=r+1
for i in range(0,(r+len(data))):
p=(2**c)
if(p==(i+1)):
h.append(0)
c=c+1
else:
h.append(int(data[j]))
j=j+1
for parity in range(0,(len(h))):
ph=(2**ch)
if(ph==(parity+1)):
startIndex=ph-1
i=startIndex
toXor=[]
while(i<len(h)):
block=h[i:i+ph]
toXor.extend(block)
i+=2*ph
for z in range(1,len(toXor)):
h[startIndex]=h[startIndex]^toXor[z]
ch+=1
h.reverse()
print('Hamming code generated would be:- ', end="")
print(int(''.join(map(str, h))))
elif(option==2): # DETECT ERROR IN RECEIVED HAMMING CODE
print('Enter the hamming code received')
d=input()
data=list(d)
data.reverse()
c,ch,j,r,error,h,parity_list,h_copy=0,0,0,0,0,[],[],[]
for k in range(0,len(data)):
p=(2**c)
h.append(int(data[k]))
h_copy.append(data[k])
if(p==(k+1)):
c=c+1
for parity in range(0,(len(h))):
ph=(2**ch)
if(ph==(parity+1)):
startIndex=ph-1
i=startIndex
toXor=[]
while(i<len(h)):
block=h[i:i+ph]
toXor.extend(block)
i+=2*ph
for z in range(1,len(toXor)):
h[startIndex]=h[startIndex]^toXor[z]
parity_list.append(h[parity])
ch+=1
parity_list.reverse()
error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))
if((error)==0):
print('There is no error in the hamming code received')
elif((error)>=len(h_copy)):
print('Error cannot be detected')
else:
print('Error is in',error,'bit')
if(h_copy[error-1]=='0'):
h_copy[error-1]='1'
elif(h_copy[error-1]=='1'):
h_copy[error-1]='0'
print('After correction hamming code is:- ')
h_copy.reverse()
print(int(''.join(map(str, h_copy))))
else:
print('Option entered does not exist')