Replies: 3 comments 2 replies
-
By co-incedence I have a need for just such a function on something I have planned (which has a 9m serial cable running up my boats mast, checksumming that is on my ideas list) . Thank you! |
Beta Was this translation helpful? Give feedback.
-
It's perhaps worth noting that this type of checksum, while widely used, is not very robust. The checksum may not detect a message containing two single bit errors in the same bit position. CRC algorithms (cyclic redundancy code) are more heavy-duty. |
Beta Was this translation helpful? Give feedback.
-
If you want the code in a usable form and not broken by copypasta, here it is: # bytes
bytes_msg_without_checksum = b"0\xc6\xf7UV\xac\x03A\xbd\xc2\x8fB\x12\xae\x14Dz\x81XA\x00\x8b\xde?\x95\xe4\xe7\x04\xd2"
bytes_msg_with_checksum = b"0\xc6\xf7UV\xac\x03A\xbd\xc2\x8fB\x12\xae\x14Dz\x81XA\x00\x8b\xde?\x95\xe4\xe7\x04\xd2\x9e"
# hex strings
hex_msg_without_checksum = (
"30c6f75556ac0341bdc28f4212ae14447a815841008bde3f95e4e704d2"
)
hex_msg_with_checksum = (
"30c6f75556ac0341bdc28f4212ae14447a815841008bde3f95e4e704d29e"
)
def checksum(msg: bytes | str) -> bytes | str | None:
"""
Calculates the 8-bit checksum of bytes or a hexadecimal string.
:param msg: Bytes or hex string to sum
:return: One bytes or one byte hex string of the sum, or None if msg type is not bytes or hex string
:note: The last 256 modulo is for a message content with 0, summed as 0x100
"""
m = 256 # 8-bit checksum modulo value
msg_type = type(msg)
if msg_type is bytes:
return ((m - sum(msg) % m) % m).to_bytes(1, "little")
elif msg_type is str:
return f"{((m - (sum(bytes.fromhex(msg))) % m) % m):02x}"
else:
return None
def main():
print(checksum(bytes_msg_without_checksum))
print(checksum(bytes_msg_with_checksum))
print(checksum(hex_msg_without_checksum))
print(checksum(hex_msg_with_checksum))
print(checksum(1.23))
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Beta Was this translation helpful? Give feedback.
All reactions