概述
import random
def sender(m, g):
m = list(m)
g = list(map(lambda x: int(x), list(g)))
crc_number = len(g)
info = m.copy()
info = list(map(lambda x: int(x), info))
times = len(info)
n = crc_number
for i in range(crc_number - 1):
info.append(0)
q = []
for i in range(times):
if info[i] == 1:
q.append(1)
for j in range(n):
info[j + i] = info[j + i] ^ g[j]
else:
q.append(0)
check_code = info[-(crc_number - 1)::]
code = m.copy()
for i in check_code:
code.append(str(i))
return "".join(code)
def receiver(check_code, g):
info = list(check_code)
info = list(map(lambda x: int(x), info))
g = list(map(lambda x: int(x), list(g)))
times = len(info)
q = []
n = len(g)
for i in range(times - len(g) + 1):
if info[i] == 1:
q.append(1)
for j in range(n):
info[j + i] = info[j + i] ^ g[j]
else:
q.append(0)
check_code = info[-(len(g) - 1)::]
for i in check_code:
if i == 1:
return False
return True
def test1(info, G):
info_crc = sender(info, G)
if receiver(info_crc, G):
print("info is {}, G is {}, info_crc is {}".format(info, G, info_crc))
else:
print("info is {}, G is {}, info_crc is not {}".format(info, G, info_crc))
def test2(info, G):
info_crc = sender(info, G)
info_crc1 = list(info_crc)
rand_index = random.randint(0,len(info_crc1) - 1)
info_crc1[rand_index] = str(1 - int(info_crc1[rand_index]))
if receiver("".join(info_crc1), G):
print("info is {}, G is {}, info_crc is {}".format(info, G, info_crc))
else:
print("info is {}, G is {}, info_crc is not {}, right is {}".format(info, G, "".join(info_crc1), info_crc))
def test3(info, G):
info_crc = sender(info, G)
sender(info_crc, G)
if receiver(info_crc, G):
print("info is {}, G is {}, info_crc is {}".format(info, G, info_crc))
else:
print("info is {}, G is {}, info_crc is not {}".format(info, G, info_crc))
print("test1 is right case. the result is: ")
test1(G="1101",
info="1101011")
print("****************")
print("test2 is designed to test the error code. the result is: ")
test2(G="1101",
info="1101011")
print("****************")
print("test3 is right case and is different from test1's G. the result is: ")
test3(G="11001",
info="10110011")
最后
以上就是哭泣钢笔为你收集整理的Python实现CRC校验的全部内容,希望文章能够帮你解决Python实现CRC校验所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复