Last active
January 5, 2017 00:58
-
-
Save Julien00859/cb6c4c355223b8c0fbaf2acba9e127aa to your computer and use it in GitHub Desktop.
CRC Computation
This file contains 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
ATM = 0b100000111 | |
AAL = 0b11000110011 | |
CCITT41 = 0b10001000000100001 | |
IEEE802 = 0b100000100110000010001010110110101 | |
def compute_crc(frame: bytes, crc: int = 0, poly: int = ATM) -> int: | |
"""Compute the CRC of the given frame | |
>>> crc = compute_crc(b"Hello world !") | |
>>> compute_crc(b"Hello world !", crc) == 0 | |
True | |
>>> compute_crc(b"Good bye !", crc) != 0 | |
True | |
""" | |
window = 0 | |
byteno = 0 | |
end = False | |
while True: | |
while window.bit_length() < poly.bit_length(): | |
if byteno < len(frame): | |
window = (window << 8) | frame[byteno] | |
byteno += 1 | |
elif end: | |
return window | |
else: | |
end = True | |
window = (window << (poly.bit_length() - 1)) | crc | |
rest_window_length = window.bit_length() - poly.bit_length() | |
crc_window = window >> rest_window_length | |
rest_window = window & ~(~0 << rest_window_length) | |
window = ((crc_window ^ poly) << rest_window_length) | rest_window | |
if __name__ == "__main__": | |
from doctest import testmod | |
testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment