从 python 中的位总和生成校验和

Checksum Generation from sum of bits in python

我正在尝试使用 python 通过 RS232 控制冷水机。我坚持按照以下方法生成校验和。

"The checksum is two ASCII hexadecimal bytes representing the least significant 8 bits of the sum of all preceding bytes of the command starting with the sor."

本例中的 "sor" 字节为“2E”。

-例子
例如,PC 需要将制冷机模式设置为待机。它将传输以下字节序列。 2E 47 30 4135 0D

注意2Eh是header(“.”)的开始,47h是命令(“G”),30h是设置模式为Stand by的限定符。 41h 和 35h 是表示“A5”的 ASCII 十六进制校验和字节,它是 2Eh + 47h + 30h 和 0Dh 之和的最低有效字节 return.

有谁知道如何生成校验和字节 4135?

谢谢!!

您可以找到十六进制的总和,如

>>> hexsum = hex(0x2e + 0x47 + 0x30)[2:].upper()
>>> hexsum
'A5'

(前面的0x[2:]减去sliced)

然后就可以得到字符的十六进制ASCII值如

>>> bytes = [hex(ord(c))[2:] for c in hexsum]
>>> bytes
['41', '35']

(同样,正面 0x 从每个元素中删除)

然后你可以 join 他们一起:

>>> checksum = ''.join(bytes)
>>> checksum
'4135'

或者一切都可以用这个一行完成:

>>> ''.join(hex(ord(c))[2:] for c in hex(0x2e + 0x47 + 0x30)[2:].upper())
'4135'

Python 2

函数rs232_checksum计算字节总和。 然后它将总和转换为大写的十六进制字符串,returns 为字节。

def rs232_checksum(the_bytes):
    return bytes('%02X' % (sum(map(ord, the_bytes)) % 256))

checksum_bytes = rs232_checksum(b'\x2e\x47\x30')

Python 3

函数定义简化为(用二进制"and"得到最低有效八位):

def rs232_checksum(the_bytes):
    return b'%02X' % (sum(the_bytes) & 0xFF)