-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchecksum.py
More file actions
66 lines (47 loc) · 1.51 KB
/
checksum.py
File metadata and controls
66 lines (47 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
A set of tools for working with simple one-byte (modulo-256) checksums.
"""
def calculate(buffer):
"""Calculate modulo-256 sum of all bytes in a buffer (a byte string or array).
Works with any kind of lists (produces a modulo-256 sum of all elements).
>>> calculate(b"\x01\x02\x03\x04\x05")
15
>>> calculate(bytearray.fromhex("22 01 10 00 00 AA AA"))
135
>>> calculate([256, 512, 1024, 1])
1
>>> calculate(b"")
0
"""
return sum(buffer) & 0xFF
def is_valid(buffer):
"""Return true if checksum at the end of a buffer is valid
(i.e. matches to the sum of all bytes in the buffer except the last one).
>>> is_valid(bytearray.fromhex("55 02 12 00 00 00 01 6A"))
True
>>> is_valid(bytearray.fromhex("55 02 12 00 00 00 01 69"))
False
>>> is_valid(bytes.fromhex("00"))
True
>>> is_valid(b"")
True
>>> is_valid([512, 32768, 0])
True
"""
return (len(buffer) == 0) or (buffer[-1] == calculate(buffer[0:-1]))
def append_to(buffer):
"""Calculate modulo-256 sum of all bytes in a given byte array
and append the checksum to the end of the array.
>>> buffer = bytearray.fromhex("55 01 12 00 00 00 10")
>>> append_to(buffer)
>>> buffer == bytearray.fromhex("55 01 12 00 00 00 10 78")
True
>>> buffer = bytearray()
>>> append_to(buffer)
>>> buffer == bytearray.fromhex('00')
True
"""
buffer.append(calculate(buffer))
if __name__ == "__main__":
import doctest
doctest.testmod()