-
Notifications
You must be signed in to change notification settings - Fork 0
/
hamming74.py
77 lines (51 loc) · 1.28 KB
/
hamming74.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
import numpy as np;
import pandas as pd;
#
# Define hamming(7,4) encoder
#
def encode_hamming74 (data_bits):
# assert len(data_bits) == 4, "Input must be nibble";
if len(data_bits) != 4:
print('hello world');
d1, d2, d3, d4 = data_bits;
p1 = d1^d2^d4;
p2 = d1^d3^d4;
p3 = d2^d3^d4;
return [p1, p2, d1, p3, d2, d3, d4];
#
# Define hamming(7,4) decoder
#
def decode_hamming74 (encoded_bits):
if len(encoded_bits) != 7:
print('wtf');
return;
p1,p2,d1,p3,d2,d3,d4 = encoded_bits;
p1_check = p1^d1^d2^d4;
p2_check = p2^d1^d3^d4;
p3_check = p3^d2^d3^d4;
error_check = 1*p1_check + 2*p2_check + 4*p3_check;
if error_check:
print(f'ERROR AT {error_check-1}');
encoded_bits[error_check-1] ^= 1;
return [encoded_bits[2], encoded_bits[4], encoded_bits[5], encoded_bits[6]];
#
# Test
# • encode a 4 bit message
# • flip a bit to simulate an error
# • pass to decoder for error detection + correction
#
data = [1,1,0,1];
data_encode = encode_hamming74(data);
data_encode[6] ^= 1;
data_decode = decode_hamming74(data_encode);
print(f'Original: {data}');
print(f'Encoded: {data_encode}');
print(f'Decoded: {data_decode}');
#
# Example Output
#
# >>> python3 hamming74.py
# ERROR AT 6
# Original: [1, 1, 0, 1]
# Encoded: [1, 0, 1, 0, 1, 0, 1]
# Decoded: [1, 1, 0, 1]