Python实现CRC校验


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")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值