Skip to content

Instantly share code, notes, and snippets.

@nzjrs
Created October 28, 2014 10:48
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 nzjrs/a5f124ab494d66576bd4 to your computer and use it in GitHub Desktop.
Save nzjrs/a5f124ab494d66576bd4 to your computer and use it in GitHub Desktop.
Non-table based implementations of crc16 and crc8-maxim
import crcmod.predefined
def _crc16(crc, c):
crc ^= ord(c)
for i in range(8):
if crc & 0x1:
crc = (crc >> 1) ^ 0xA001
else:
crc = (crc >> 1)
return crc
def crc16(s):
crc = 0
for c in s:
crc = _crc16(crc,c)
return crc
def _crc8maxim(crc, c):
crc ^= ord(c)
for i in range(8):
if crc & 0x1:
crc = (crc >> 1) ^ 0x8C
else:
crc = (crc >> 1)
return crc
def crc8maxim(s):
crc = 0
for c in s:
crc = _crc8maxim(crc,c)
return crc
if __name__ == "__main__":
S = 'test124'
print "CRC16 (%s)" % S
crc = crcmod.predefined.Crc('crc-16')
crc.update(S)
print hex(crc.crcValue), 'vs', hex(crc16(S))
print "CRC8 (%s)" % S
crc = crcmod.predefined.Crc('crc-8-maxim')
crc.update(S)
print hex(crc.crcValue), 'vs', hex(crc8maxim(S))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment