TG-PlatformPlus/scripts/check_CRC16.pys

35 lines
890 B
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

def check_value(data: bytes) -> int:
# 初始化crc为0xFFFF
crc = 0xFFFF
# 循环处理每个数据字节
for byte in data:
# 将每个数据字节与crc进行异或操作
crc ^= byte
# 对crc的每一位进行处理
for _ in range(8):
# 如果最低位为1则右移一位并执行异或0xA001操作(即0x8005按位颠倒后的结果)
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
# 如果最低位为0则仅将crc右移一位
else:
crc = crc >> 1
retH = int(crc / 256)
retL = int(crc % 256)
return retL * 256 + retH
def check(data: bytes) -> int:
if len(data) < 2:
return False
crc = check_value(data[:-2])
crc_in_frame = data[-1] + data[-2] * 256
if crc == crc_in_frame:
return True
return False