Python crc_hqx(data, value) proper implementation

Question:

Solved! Thank you rcgdlr.

I am just learning about CRCs and am unsure my implementation is correct. I have a number of questions:

  1. Do I include the crc in the data portion (I believe I do but I’m unsure; could it depend on the implementation)?

    bytes_trans = cmd_in[5:-2]  # -2 to incl crc or -4 to excl crc?
    
  2. How do I determine my initial value? Most implementations I saw online either used 0 or passed the crc itself. I have tried these two methods:

    # CRC from the message
    crc_start = int.from_bytes(cmd_in[-4:-2], byteorder='little', signed=False) 
    
    crc = binascii.crc_hqx(bytes_trans, crc_start)
    
    crc2 = binascii.crc_hqx(bytes_trans, 0)
    
  3. How do I know when it works? I believe I’m looking for either a 0 out or an integer that matches the CRC?

  4. I have not had success thus far which suggests I’m using the wrong inputs or the CRC is not actually a CCITT CRC-16 as specified in the documentation I am working from. I have tried most PyCRC implementations e.g. DNP and Kermit but have also had no luck. Is there a way to confirm that I am indeed working with a CCITT CRC-16? Are there factors that could have been implemented differently making this a slightly modified CCITT CRC-16?

Asked By: Bix

||

Answers:

Normally a CRC is appended to data, most significant byte first.

The initial value depends on the specific implementation. For 16 bit CRC, the two most common values are 0x0000 or 0xffff. In some cases other values are used, the most common of these would be the equivalent of an initial value of 0x0000, and generating at CRC for the two byte data string 0xff, 0xff, as if the data was prefixed with the two byte pattern 0xff, 0xff.

To check your CRC implementation, you can compare it with one of the CRC’s from a web site such as:

https://www.lammertbies.nl/comm/info/crc-calculation.html

Using the hex input option is more flexible. When comparing your implementation, do not append your calculated CRC to the data when entering your data on the web site entry box.

Answered By: rcgldr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.