-
-
Notifications
You must be signed in to change notification settings - Fork 50.8k
Expand file tree
/
Copy pathhamming_code.py
More file actions
91 lines (75 loc) · 2.41 KB
/
Copy pathhamming_code.py
File metadata and controls
91 lines (75 loc) · 2.41 KB
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
def calculate_parity_bits(data_bits: list[int]) -> int:
"""
Calculates the number of redundant parity bits needed for Hamming Code.
>>> calculate_parity_bits([1, 0, 1, 1])
3
"""
m = len(data_bits)
r = 0
while (2**r) < (m + r + 1):
r += 1
return r
def hamming_encode(data_str: str) -> str:
"""
Encodes a binary string into a Hamming Code (7,4 or adaptive format).
Features error detection parity implementation.
>>> hamming_encode("1011")
'1010101'
"""
data = [int(x) for x in data_str]
r = calculate_parity_bits(data)
m = len(data)
# Initialize code word with placeholders (0)
code = [0] * (m + r)
# Place data bits into non-parity positions
j = 0
for i in range(1, len(code) + 1):
if (i & (i - 1)) != 0: # Not a power of 2
code[i - 1] = data[j]
j += 1
# Calculate parity bits using XOR logic
for i in range(r):
parity_pos = 2**i
parity_val = 0
for j in range(1, len(code) + 1):
if j & parity_pos and j != parity_pos:
parity_val ^= code[j - 1]
code[parity_pos - 1] = parity_val
return "".join(map(str, code))
def hamming_decode_and_correct(code_str: str) -> tuple[str, int]:
"""
Decodes the Hamming code, detects, and automatically corrects a single-bit error.
Returns a tuple of (corrected_data_bits_string, error_position).
>>> hamming_decode_and_correct("1010101")
('1011', 0)
>>> hamming_decode_and_correct("1010111") # Error injected at position 6
('1011', 6)
"""
code = [int(x) for x in code_str]
n = len(code)
# Determine number of parity bits r
r = 0
while (2**r) <= n:
r += 1
error_pos = 0
# Check each parity bit syndrome
for i in range(r):
parity_pos = 2**i
parity_sum = 0
for j in range(1, n + 1):
if j & parity_pos:
parity_sum ^= code[j - 1]
if parity_sum != 0:
error_pos += parity_pos
# Correct the error if detected
if error_pos > 0:
code[error_pos - 1] ^= 1 # Flip the corrupted bit
# Extract original data bits
original_data = []
for i in range(1, n + 1):
if (i & (i - 1)) != 0:
original_data.append(code[i - 1])
return "".join(map(str, original_data)), error_pos
if __name__ == "__main__":
import doctest
doctest.testmod()