CRC 循环冗余校验原理 Python 实现

  • Post author:
  • Post category:python


def get_b_code(code_str):
    code_lst = []
    for c in code_str:
        code_lst.append(int(c))
    return code_lst

def print_b_code(code):
    code_str = ''
    for c in code:
        code_str+=str(c)
    print(code_str)
    
def backward_insert(code_lst, num):
    result = []
    for c in code_lst:
        result.append(c)
    result.append(num)
    return result

def YH(code_lst1, code_lst2, len_mode = '-1'):
    if len(code_lst1) != len(code_lst2):
        print('No same len')
        return None
    else:
        def bit_cal(a,b):
            if (a+b == 2) or (a+b==0):
                return 0
            else:
                return 1
        result = []
        for idx in range(len(code_lst1)):
            result.append(bit_cal(code_lst1[idx],code_lst2[idx]))
        if len_mode=='-1':
            result = result[1:]
        return result
        
def CRC(bc, code):
    Q_result = [1]
    bc = get_b_code(bc)
    code = get_b_code(code)
    code_cal = code.copy()
    for i in range(len(bc)-1):
        code_cal.append(0)
    #print_b_code(code_cal)
    below_stack = code_cal[len(bc):]
    start_code = code_cal[:len(bc)]
    tmp = start_code.copy()
    point = 1
    for below in below_stack:
        new_bc = bc.copy()
        new_bc = [ b*point for b in bc ]
        tmp = YH(tmp, new_bc)
        #print_b_code(tmp)
        if tmp[0] == 0:
            point = 0
            Q_result.append(0)
        else:
            point = 1
            Q_result.append(1)
        #print(below)
        tmp = backward_insert(tmp, below)
    
    #print_b_code(Q_result)
    new_bc = bc.copy()
    new_bc = [ b*point for b in bc ]
    tmp = YH(tmp, new_bc)
    return Q_result, tmp

bc = '10011'
code = '1101011011'

Q,R = CRC(bc, code)
print_b_code(Q)
print_b_code(R)

在这里插入图片描述

打印出:

Q = 1100001010
R = 1110



版权声明:本文为rizero原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。