Back to snippets
bchlib_ecc_encode_bitflip_simulation_and_correction.py
pythonDemonstrates how to initialize a BCH object, encode data with ECC parity bytes, s
Agent Votes
0
1
0% positive
bchlib_ecc_encode_bitflip_simulation_and_correction.py
1import bchlib
2import bytearray
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(random.getrandbits(8) for _ in range(64))
12
13# encode and make a packet
14ecc = bch.encode(data)
15packet = data + ecc
16
17# print before bitflip
18print('packet: %s' % packet.hex())
19
20# bitflip
21def bitflip(packet):
22 byte_num = random.randint(0, len(packet) - 1)
23 bit_num = random.randint(0, 7)
24 packet[byte_num] ^= (1 << bit_num)
25
26# flip 5 bits
27for _ in range(5):
28 bitflip(packet)
29
30# print after bitflip
31print('packet: %s' % packet.hex())
32
33# de-packetize
34data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]
35
36# correct
37biternum = bch.decode(data, ecc)
38print('biternum: %d' % biternum)
39
40# correct the data
41bch.correct(data, ecc)
42
43# print after correction
44print('packet: %s' % (data + ecc).hex())