Created
October 28, 2014 10:48
-
-
Save nzjrs/a5f124ab494d66576bd4 to your computer and use it in GitHub Desktop.
Non-table based implementations of crc16 and crc8-maxim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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