This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhamming
executable file
·74 lines (53 loc) · 1.98 KB
/
hamming
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
#!/usr/bin/env python
from typing import Tuple
"""
Script to solve problems on 11-bit Hamming Code used in
Networks and Internet Systems.
### Usage: `$ ./hamming`
"""
def main() -> None:
op = int(input("1. 11-bit Hamming Encoder\n" +
"2. Detect and Correct Error\n" +
"Choose option 1 or 2:\t"))
if op == 1:
seq = input('\nEnter 7-bit sequence:\t')
print(f"Hamming code (11-bit):\t{getCode(seq)}")
elif op == 2:
seq = input('\nInput 11-bit sequence:\t')
exists, error_bit, correct_seq = checkError(seq)
data = dataSent(correct_seq)
print(f"Error exists:\t\t{exists}\n" +
f"Error bit:\t\t{error_bit}\n" +
f"Correct Sequence:\t{correct_seq}\nData Sent:\t\t{data}")
else:
print('Please try again!')
def getCode(seq: str) -> str:
bits = [int(bit) for bit in seq]
for i in [3, 7, 9, 10]:
bits.insert(i, 0)
bits[10] = parity(bits, 0, 2, 4, 6, 8) # r1
bits[9] = parity(bits, 0, 1, 4, 5, 8) # r2
bits[7] = parity(bits, 4, 5, 6) # r4
bits[3] = parity(bits, 0, 1, 2) # r8
return ''.join([str(b) for b in bits])
def parity(bits: list, *indices: int) -> int:
return sum([bits[i] for i in indices]) % 2
def checkError(seq: str) -> Tuple[bool, int, str]:
bits = [int(bit) for bit in seq]
p1 = parity(bits, 0, 2, 4, 6, 8, 10)
p2 = parity(bits, 0, 1, 4, 5, 8, 9)
p4 = parity(bits, 4, 5, 6, 7)
p8 = parity(bits, 0, 1, 2, 3)
new_parity = ''.join([str(i) for i in [p8, p4, p2, p1]])
error_bit = int(new_parity, 2)
exists = error_bit != 0
if exists:
idx = 11 - error_bit
bits[idx] = int(not bits[idx])
correct_seq = ''.join([str(b) for b in bits])
return (exists, error_bit, correct_seq)
def dataSent(correct_seq: str) -> str:
bits = list(correct_seq)
return ''.join([b for i, b in enumerate(bits) if i not in [3, 7, 9, 10]])
if __name__ == '__main__':
main()