Arash
Arash

Reputation: 264

How to calculate CRC in python

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

Upvotes: 0

Views: 3134

Answers (1)

Mark Adler
Mark Adler

Reputation: 112547

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.

Upvotes: 2

Related Questions