-
Notifications
You must be signed in to change notification settings - Fork 0
/
hamming.py
64 lines (56 loc) · 2.21 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
def hamming_decode(msg: str) -> str: # TODO : Utiliser un type bytes/binary au lieu de string
"""
Décode un message encodé avec le code de Hamming, corrige les erreurs et retire les bits de redondance
:param msg: Message encodé avec le code de Hamming
:return: Message décodé, corrige et sans bits de redondance
"""
result = ""
for i in range(0, len(msg), 7):
buffer = msg[i:i + 4]
redondance = [
int(msg[i + 4]),
int(msg[i + 5]),
int(msg[i + 6])
]
computedRedondance = [
int(buffer[0]) ^ int(buffer[1]) ^ int(buffer[2]),
int(buffer[0]) ^ int(buffer[1]) ^ int(buffer[3]),
int(buffer[1]) ^ int(buffer[2]) ^ int(buffer[3])
]
if redondance != computedRedondance:
# Calcul de la position de l'erreur
redondanceDistance = [
redondance[0] == computedRedondance[0],
redondance[1] == computedRedondance[1],
redondance[2] == computedRedondance[2]
]
errorIndex = 0
match redondanceDistance:
case [False, False, True]:
errorIndex = 0
case [False, False, False]:
errorIndex = 1
case [False, True, False]:
errorIndex = 2
case [True, False, False]:
errorIndex = 3
# Correction de l'erreur
buffer = list(buffer)
buffer[errorIndex] = str(int(buffer[errorIndex]) ^ 1)
buffer = "".join(buffer)
result += buffer
return result
def hamming_encode(msg: str) -> str: # TODO : Utiliser un type bytes/binary au lieu de string
"""
Encode un message avec le code de Hamming
:param msg: Message à encoder
:return: Message encodé avec le code de Hamming
"""
result = ""
for i in range(0, len(msg), 4):
buffer = msg[i:i + 4]
result += buffer
result += str(int(buffer[0]) ^ int(buffer[1]) ^ int(buffer[2]))
result += str(int(buffer[0]) ^ int(buffer[1]) ^ int(buffer[3]))
result += str(int(buffer[1]) ^ int(buffer[2]) ^ int(buffer[3]))
return result