Skip to content

Instantly share code, notes, and snippets.

@nmiglio
Last active May 23, 2019 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmiglio/01b244da2318fed140e1c9ca8138d295 to your computer and use it in GitHub Desktop.
Save nmiglio/01b244da2318fed140e1c9ca8138d295 to your computer and use it in GitHub Desktop.
Python script to evaluate CRC16 CCITT (0xffff)
# Computation of CRC16 CCITT (0xFFFC)
# The input parameter for crc16Eval() is a hexString obtained from a bytearray bytes values
# The function returns a string with the hexadecimal value, an int with the low byte value
# and an int with the high byte value of the crc.
#
# hexArray = bytearray(b'\xe8\x8a\x04\r\x00W\x8b')
# hexString = = "".join(map(chr, hexArray))
# (crcHexStr, crcHighByte, crcLowByte) = crc16Eval(hexString)
class CRC_CCITT:
def __init__(self):
self.tab = 256*[[]]
for i in range(256):
crc = 0
c = i << 8
for j in range(8):
if (crc ^ c) & 0x8000:
crc = ( crc << 1) ^ 0x1021
else:
crc = crc << 1
c = c << 1
crc = crc & 0xffff
self.tab[i]=crc
def update_crc(self, crc, c):
short_c=0x00ff & (c % 256)
tmp = ((crc >> 8) ^ short_c) & 0xffff
crc = (((crc << 8) ^ self.tab[tmp])) & 0xffff
return crc
def crc16Eval(byteStr):
crc_ccitt = CRC_CCITT()
crcVal=0xffff
for c in byteStr:
crcVal=crc_ccitt.update_crc(crcVal, ord(c))
# crcVal=crc_ccitt.update_crc(crcVal, 0)
crcHigh = crcVal >> 8
crcLow = crcVal & 0x00ff
return(hex(crcVal), crcHigh, crcLow)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment