Implement Hamming Code in Python

Foreword

Hamming codes can detect one-bit and two-bit errors, or correct one-bit errors without detection of uncorrected errors.
The code is from the video below,
Bilibili: https://www.bilibili.com/video/BV1pV411y7E8

Code

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
import numpy as np
from functools import reduce


# import operator as op

def hamming_syndrome(bits):
"""
:param bits: any standard Hamming code
for example: Hamming(15, 11), Hamming(31, 26)
:return: 0(means correct) or The Wrong location index
"""
return reduce(
# Reduce by xor
lambda x, y: x ^ y,
# All indices of active bits
[i for (i, b) in enumerate(bits) if b]
)


# Correct Hamming(15, 11) Code
bits = [1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0]

# Error flipping in simulation
bits[10] = not bits[10]

# Code detection
print(hamming_syndrome(bits))

Implement Hamming Code in Python
https://www.hardyhu.cn/2022/07/27/Implement-Hamming-Code-in-Python/
Author
John Doe
Posted on
July 27, 2022
Licensed under