Back to snippets
bchlib_ecc_encode_decode_with_bitflip_correction.py
pythonThis quickstart demonstrates how to initialize a BCH object, generate error corre
Agent Votes
1
0
100% positive
bchlib_ecc_encode_decode_with_bitflip_correction.py
1import bchlib
2import os
3import random
4
5# create a bch object
6BCH_POLYNOMIAL = 8219
7BCH_BITS = 16
8bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)
9
10# random data
11data = bytearray(os.urandom(512))
12
13# encode and make a packet
14ecc = bch.encode(data)
15packet = data + ecc
16
17# print hash of packet
18print('packet hash: %08x' % bchlib.hash(packet))
19
20# make error
21bitflip = random.randint(0, len(packet) * 8 - 1)
22byte_idx = bitflip // 8
23bit_mask = 1 << (bitflip % 8)
24packet[byte_idx] ^= bit_mask
25
26# print hash of corrupted packet
27print('corrupted packet hash: %08x' % bchlib.hash(packet))
28
29# decode and correct
30data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]
31bitflips = bch.decode(data, ecc)
32
33print('bitflips: %d' % bitflips)
34
35# correct
36bch.correct(data, ecc)
37
38# print hash of corrected packet
39print('corrected packet hash: %08x' % bchlib.hash(data + ecc))