CRC校验的python实现
参考链接:https://www.jianshu.com/p/8185e125afaf
实现步骤
- 选择合适的生成多项式
- 将原始信息左移生成多项式阶数减一位
- 将左移后的信息与生成多项式模二相除得到余数,余数即校验码(校验码位数比生成多项式阶数小一,高位0不能省略)
- 将检验码附加在原信息后
源代码
import numpy as np
class CRC:
def __init__(self, info_list, crc_n=32):
self.info_list = info_list
# 初始化生成多项式p
loc = [32, 26, 23, 22, 16, 12, 11, 10, 8, 7, 5, 2, 1, 0]
p = [0 for i in range(crc_n + 1)]
for i in loc:
p[i] = 1
info_list = self.info_list.copy()
times = len(info_list)
n = crc_n + 1
# 左移补零
for i in range(crc_n):
info_list.append(0)
# 除
q = []
for i in range(times):
if info_list[i] == 1:
q.append(1)
for j in range(n):
info_list[j + i] = info_list[j + i] ^ p[j]
else:
q.append(0)
# 余数
check_code = info_list[-crc_n::]
# 生成编码
code_list = self.info_list.copy()
for i in check_code:
code_list.append(i)
self.crc_n = crc_n
self.p = p
self.q = q
self.check_code = check_code
self.code_list = code_list
def print(self):
info_str = ''.join('%s' % id for id in self.info_list)
code_str = ''.join('%s' % id for id in self.code_list)
p_str = ''.join('%s' % id for id in self.p)
q_str = ''.join('%s' % id for id in self.q)
check_code_str = ''.join('%s' % id for id in self.check_code)
print('信息:', info_str)
print('生成多项式:', p_str)
print('商:', q_str)
print('余数:', check_code_str)
print('编码:', code_str)
测试
m = np.random.randint(0, 2, 10)
m = list(m)
crc = CRC(m, 32)
n = list(crc.code_list)
crc.print()
check_code = CRC(n, 32).check_code
'''
print('检验余数:', ''.join('%s' % id for id in check_code))
'''
flag = 0
for i in range(len(check_code)):
if check_code[i] == 1:
flag = 1
break
if flag == 0:
print("传输数据无误")
else:
print("传输数据有误")
输出
信息: 0100010101
生成多项式: 111001011011100010000011001000001
商: 0110100011
余数: 11111010001101101010001101100011
编码: 010001010111111010001101101010001101100011
检验余数: 00000000000000000000000000000000
传输数据无误```