Created
November 27, 2012 01:15
-
-
Save kurtbrose/4151765 to your computer and use it in GitHub Desktop.
create an efficient(-ish) CRC16 computation from an arbitrary taps polynomial
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
| ''' | |
| See 16 bit values from here: | |
| http://en.wikipedia.org/wiki/Cyclic_redundancy_check#Commonly_used_and_standardized_CRCs | |
| for some commonly used values for taps. | |
| Since this implementation uses right shifting, take the values from the 'reversed' column. | |
| Some examples: 0xA001, 0x8408, 0xEDD1, 0xA6BC, 0x91A0, 0xD405 | |
| These are all maximal taps; that is, the permutation over integers mod 2**16 that they define | |
| has one giant cycle rather than multiple small cycles. | |
| ''' | |
| class CRC16(object): | |
| def __init__(self, taps): | |
| table = [] | |
| for i in range(0xFF): | |
| val = i << 8 | |
| for j in range(16): | |
| val = (val >> 1) ^ ( -(val&1) & taps) | |
| table.append(val) | |
| self.table = tuple(table) | |
| def crc16(self, data): | |
| table = self.table | |
| crc = 0 | |
| for byte in data: | |
| crc = (crc>>8) ^ table[(crc ^ ord(byte)) & 0xFF] | |
| return crc | |
| def add_crc(self, data): | |
| crc = self.crc16(data) | |
| return data + chr(crc & 0xFF) + chr(crc>>8) | |
| def check_crc(self, data): | |
| return self.crc16(data) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment