-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRCCCITT.py
61 lines (45 loc) · 1.93 KB
/
CRCCCITT.py
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
#!/usr/bin/env python
# -*- coding: utf8 -*-
# CRC CCITT
#
# comes in 3 flavous
# (XModem) starting value: 0x0000
# starting value: 0xffff
# starting value: 0x1d0f
#
# Cristian NAVALICI cristian.navalici at gmail dot com
from ctypes import c_ushort
class CRCCCITT(object):
crc_ccitt_tab = []
# The CRC's are computed using polynomials. Here is the most used coefficient for CRC CCITT
crc_ccitt_constant = 0x1021
def __init__(self, version = 'XModem'):
try:
dict_versions = { 'XModem':0x0000, 'FFFF':0xffff, '1D0F':0x1d0f }
if version not in dict_versions.keys():
raise Exception("Your version parameter should be one of the {} options".format("|".join(dict_versions.keys())))
self.starting_value = dict_versions[version]
if not len(self.crc_ccitt_tab): self.init_crc_ccitt() # initialize the precalculated tables
except Exception, e:
print e
def calculate(self, string = ''):
try:
if not isinstance(string, str): raise Exception("Please provide a string as argument for calculation.")
if not string: return 0
crcValue = self.starting_value
for c in string:
tmp = (c_ushort(crcValue >> 8).value) ^ ord(c)
crcValue = (c_ushort(crcValue << 8).value) ^ int(self.crc_ccitt_tab[tmp], 0)
return crcValue
except Exception, e:
print "EXCEPTION(calculate): {}".format(e)
def init_crc_ccitt(self):
'''The algorithm use tables with precalculated values'''
for i in range(0, 256):
crc = 0
c = i << 8
for j in range(0, 8):
if ((crc ^ c) & 0x8000): crc = c_ushort(crc << 1).value ^ self.crc_ccitt_constant
else: crc = c_ushort(crc << 1).value
c = c_ushort(c << 1).value # equiv c = c << 1
self.crc_ccitt_tab.append(hex(crc))