Skip to content

Instantly share code, notes, and snippets.

@sugiana
Created October 16, 2013 13:28
Show Gist options
  • Save sugiana/7007722 to your computer and use it in GitHub Desktop.
Save sugiana/7007722 to your computer and use it in GitHub Desktop.
#!/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
def calc_polynomial(list_):
r = 0
for p in list_:
r += 2 ** p
return r
class CRCCCITT32(object):
crc_ccitt_tab = []
#polynomials = (32, 26, 23, 22, 16, 12, 11, 10, 8, 7, 5, 4, 2, 1, 0)
#crc_ccitt_constant = calc_polynomial(polynomials[1:]) # 0x04c11db7
crc_ccitt_constant = 0x1021
def __init__(self):
self.starting_value = 0x0000
if not self.crc_ccitt_tab:
self.init_crc_ccitt() # initialize the precalculated tables
def calculate(self, string = ''):
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
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))
crc = CRCCCITT32()
x = '\x04\x03\x02\x01\x08\x07\x06\x05'
crc.calculate(x)
r = crc.calculate(x)
print(hex(r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment