Skip to content

Instantly share code, notes, and snippets.

@APadierna
Last active April 16, 2016 22:16
Show Gist options
  • Save APadierna/7851902 to your computer and use it in GitHub Desktop.
Save APadierna/7851902 to your computer and use it in GitHub Desktop.
CRC calculator using the XModem algorithm.
#!/usr/bin/python
"""
Given a file containing hexadecimal numbers (one number per line),
returns the XModem CRC of these numbers.
Note: This scrip uses the thist party library `crcmod`.
you may isntall it using `pip install crcmod`
More info available here:
https://pypi.python.org/pypi/crcmod
"""
import binascii
import crcmod
import argparse
def main():
args = parse_input_arguments()
crc = calculate_crc(open(args.input_filename, 'r'))
print('The calculated CRC is: ' + crc)
def parse_input_arguments():
"""
Parse the input arguments.
@return args: Arguments provided by the user.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
dest="input_filename",
help="Input file",
metavar="FILE")
args = parser.parse_args()
return args
def calculate_crc(data_stream):
"""
Given a file containing hexadecimal numbers, returns the XModem CRC of these
numbers.
@param data_stream: iterable object containing hex data (str format).
@return CRC (XModem algorithm): Hex string containing the calculated CRC.
"""
xmodem_crc = crcmod.Crc(0x11021, initCrc=0, rev=False, xorOut=0x0000)
for dataword in data_stream:
xmodem_crc.update(binascii.a2b_hex(dataword.strip()))
return xmodem_crc.hexdigest()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment