sample_code/crc16_test.py
2025-03-07 00:24:33 +08:00

58 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
# @Author :幸运锦鲤
# @Time : 2025-03-07 00:22:47
# @version : python3
# @Update time :
# @Description : crc16校验码计算示例代码
'''
def crc16(data: str) -> str:
# 将输入字符串按空格分割,并将每个部分转换为字节
byte_list = [int(byte, 16) for byte in data.split()]
# 计算CRC16校验码
crc = 0xFFFF
for b in byte_list:
cur_byte = 0xFF & b
for _ in range(0, 8):
if (crc & 0x0001) ^ (cur_byte & 0x0001):
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
cur_byte >>= 1
# 将CRC16校验码转换为大端序高位在前
crc = ((crc & 0xFF) << 8) | (crc >> 8)
# 将CRC16校验码转换为两位十六进制字符串
crc_high = (crc >> 8) & 0xFF
crc_low = crc & 0xFF
crc_str = f"{crc_high:02X}{crc_low:02X}"
# 返回原始数据加上CRC16校验码的字符串无空格
return f"{data.replace(' ', '')}{crc_str}"
# 示例用法
input_data = "01 03 00 00 00 01"
result = crc16(input_data)
print(result) # 输出: "010300000001840A"
input_data = "07 04 00 00 00 02"
result = crc16(input_data)
print(result)
input_data = "05 06 00 00 00 01"
result = crc16(input_data)
print(result)
spaced_hex_str = ' '.join(result[i:i+2] for i in range(0, len(result), 2))
print("result:",spaced_hex_str)