I'm writing a Python program to extract data from the middle of a 6 GB bz2 file. A bzip2 file is made up of independently decryptable blocks of data, so I only need to find a block (they are delimited by magic bits), then create a temporary one-block bzip2 file from it in memory, and finally pass that to the bz2.decompress function. Easy, no?
The bzip2 format has a crc32 checksum for the file at the end. No problem, binascii.crc32 to the rescue. But wait. The data to be checksummed does not necessarily end on a byte boundary, and the crc32 function operates on a whole number of bytes.
My plan: Use the binascii.crc32 function on all but the last byte, and then a function of my own to update the computed crc with the last 1–7 bits. But hours of coding and testing has left me bewildered, and my puzzlement can be boiled down to this question: How come crc32("\x00") is not 0x00000000? Shouldn't it be, according to the Wikipedia article?
You start with 0b00000000 and pad with 32 0's, then do polynomial division with 0x04C11DB7 until there are no ones left in the first 8 bits, which is immediately. Your last 32 bits is the checksum, and how can that not be all zeroes?
I've searched Google for answers and looked at the code of several CRC-32 implementations without finding any clue to why this is so.
CRC32 is an error-detecting function that uses a CRC32 algorithm to detect changes between source and target data. The CRC32 function converts a variable-length string into an 8-character string that is a text representation of the hexadecimal value of a 32 bit-binary sequence.
It's reasonably fast (375 MByte/s on my computer) and comes with only a small memory overhead. Often the look-up table isn't pre-computed at runtime but rather stored as a large table in the C code.
Detecting duplicate files If you want to check if two files are the same, CRC32 checksum is the way to go because it's faster than MD5.
how come crc32("\x00") is not 0x00000000?
The basic CRC algorithm is to treat the input message as a polynomial in GF(2), divide by the fixed CRC polynomial, and use the polynomial remainder as the resulting hash.
CRC-32 makes a number of modifications on the basic algorithm:
Let's work out the CRC-32 of the one-byte string 0x00:
And there you have it: The CRC-32 of 0x00 is 0xD202EF8D.
(You should verify this.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With