Can信号CRC校验

Can信号CRC校验

def crc8sae_j1850_bit(data):
    """
    crc8sae_j1850_bit calculates the crc on an input byte array using the
    method defined in the crc8sae_j1850 standard.

    Arguments:
        data - array of bytes in the format: ['\x00', '\x01', ...]

    Returns:
        crc - a single byte containing the crc of the input data bytes

    Raises:
        - Exception if any element of the input array is longer than 1 byte
        - Exception if the length of the input array is greater than 7 bytes
    """
    if len(data) > 7 or len(data) == 0:
        raise Exception(
            'Error: data length cannot excede 7 bytes')
    crc = ord('\xff')
    for byte in data:
        if len(byte) > 1:
            raise Exception(
                'Error: data must be an array of strings of length 1')
        else:
            crc ^= ord(byte)
        for k in range(0, 8):
            if crc & ord('\x80'):
                crc = (crc << 1) ^ ord('\x1d')
            else:
                crc = crc << 1
    crc &= ord('\xff')
    crc ^= ord('\xff')
    return hex(crc)

if __name__ == "__main__":
    msg_data = "21 01 51 50 00 00 00 00"
    crc_num = 0
    msg_data_list = msg_data.split(" ")
    msg_list = [chr(int(b, 16)) for b in msg_data_list]
    print("msg list is {}".format(msg_list))
    msg_list.remove(msg_list[crc_num])
    msg_data_list[crc_num] = crc8sae_j1850_bit(msg_list).replace("0x", "")
    print("msg data list is {}".format(msg_data_list))
    msg_data = " ".join(msg_data_list)
    print("msg data is {}".format(msg_data))

发布了19 篇原创文章 · 获赞 3 · 访问量 4948

猜你喜欢

转载自blog.csdn.net/xiaojian0907/article/details/103198456