-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrc.py
More file actions
92 lines (71 loc) · 2.28 KB
/
crc.py
File metadata and controls
92 lines (71 loc) · 2.28 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import zlib
import struct
#polynomial = 0x04C11DB7
#bit_width = 32
def crc(data, polynomial = 0x4c11db7, bit_width = 32, flip = True, lsb_first = True, reverse_out = True):
value = 0
if flip:
value ^= (1 << bit_width) - 1
# for each bit
for byte in data:
for j in range(8):
bit_flag = (value >> (bit_width - 1)) ^ (byte >> (j if lsb_first else (7 - j)))
value = value << 1
if bit_flag & 1:
value ^= polynomial
value &= (1 << bit_width) - 1
if flip:
value ^= (1 << bit_width) - 1
# bit reverse
if reverse_out:
value2 = 0
for j in range(bit_width):
value2 |= ((value >> j) & 1) << (bit_width - 1 - j)
value = value2
return value
def check(a):
assert crc(a) == zlib.crc32(a)
for i in range(10):
check(b"\x00" * i)
for i in range(1, 10):
check(b"\x01" * i)
for i in range(1, 10):
check(b"\x80" * i)
check(b"123456789")
check(b"hello world")
assert crc(b"123456789") == 0xCBF43926
for i in range(1, 4):
check(b"\x55\xaa\x99" * i)
def crc16(data):
polynomial = 0x8005
bit_width = 16
return crc(data, polynomial, bit_width, False)
def crc16_ccitt_kermit(data):
polynomial = 0x1021
bit_width = 16
return crc(data, polynomial, bit_width, False)
def crc16_ccitt_xmodem(data):
polynomial = 0x1021
bit_width = 16
return crc(data, polynomial, bit_width, False, False, False)
assert crc16(b"123456789") == 0xbb3d
assert crc16_ccitt_kermit(b"123456789") == 0x2189
assert crc16_ccitt_xmodem(b"123456789") == 0x31c3
assert crc(b"") == 0
def suffix(data):
polynomial = 0x8005
bit_width = 16
value = crc(data, polynomial, bit_width, False)
more = struct.pack("<H", value)
check = crc(data + more, polynomial, bit_width, False)
assert check == 0
return value
assert suffix(b"123456789") == 0xbb3d
def test_pattern(hex_string):
num_bytes = len(hex_string) // 2
data = [int(hex_string[i:i+2], 16) for i in range(0, len(hex_string), 2)]
data.reverse()
return crc16(data)
print(hex(test_pattern("6654dbbc0a")))
print(hex(test_pattern("22ebd5cf7c")))
print(hex(test_pattern("c212151d13")))