0

My question is how should I calculate CRC? I know that when you calculate CRC, you have a checksum and you need to append this to the original data, and when you send the data+checksum together, the receiver can detect if there are any errors by simply dividing the data by a polynomial and if there is any remainder other than 0. I don't know how to append since everyone is only talking about using the codes like the following:

crc32 = crcmod.mkCrcFun(0x104c11db7, 0, False, 0xFFFFFFFF)
bytes_read = f.read(BUFFER_SIZE)
this_chunk_crc=crc32(bytes_read)#will return some integer
Arash
  • 225
  • 1
  • 11
  • what crc? for what? what's `crcmod` and `mkCrcFun`? – 2e0byo Apr 08 '22 at 18:09
  • Incidentally if your question is 'how do I go about implementing a crc algorithim in python', the [wikipedia page](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) actually contains not only a description of the algorithm but an example implementation in python. If you just want a recommended library, the question is off-topic here. – 2e0byo Apr 08 '22 at 18:12
  • @2e0byo my problem is CRC should be calculated and appended to the end of the data and after that, if anyone (receiver) calculates the CRC for themselves they need to see the remainder of 0. could you verify this statement? – Arash Apr 08 '22 at 19:11
  • crcmod is a library `import crcmod` – Arash Apr 08 '22 at 19:13

1 Answers1

2

You're already calculating the CRC. You are apparently asking how to append the CRC, an integer, to your message, a byte string.

You would use crc.to_bytes(4, 'big') to convert the returned CRC to a string of four bytes in big-endian order. You can then append that to your message. E.g.:

msg += crc32(msg).to_bytes(4, 'big')

I picked big-endian order because your CRC is defined with a False in the third argument. If that had been True (a reflected CRC), then I would have picked little-endian order, 'little'.

Having done all that correctly, the CRC of the resulting message with CRC appended will always be the same constant. But not zero in this case. The constant for that CRC definition is 0x38fb2284, or 955982468 in decimal.

Mark Adler
  • 101,978
  • 13
  • 118
  • 158
  • Thank you so much for your answer, So it doesn't relate to the message and always would be `955982468` on the receive side. am I right? – Arash Apr 09 '22 at 04:47
  • 1
    Correct........ – Mark Adler Apr 09 '22 at 04:56
  • How can I remove the checksum from the file after the receiver received it? I tried `bytes_read -= crc32(bytes_read).to_bytes(4, 'big')` without any luck. – Arash Apr 12 '22 at 04:31
  • And could you please help me with my follow up question here: https://stackoverflow.com/questions/71837210/python-socket-works-fine-when-debugging-line-by-line-but-not-working-on-the-full – Arash Apr 12 '22 at 04:45