How to calculate CRC32 checksum in Python


Cyclic redundancy check

A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to digital data.

Using zlib.crc32 Function

Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Import module
import zlib

s = b'Python'
# using zlib.crc32() method
t = zlib.crc32(s)
# lower 

Changed in version 3.0: The result is always unsigned.

CRC-32 algorithm

This is a practical algorithm for the CRC-32 variant of CRC.

Function CRC32
      data:  Bytes     // Array of bytes
      crc32: UInt32    // 32-bit unsigned CRC-32 value

// Initialize CRC-32 to starting value
crc32 ← 0xFFFFFFFF

for each byte in data do
   nLookupIndex ← (crc32 xor byte) and 0xFF;
   crc32 ← (crc32 shr 8) xor CRCTable[nLookupIndex]  // CRCTable is an array of 256 32-bit constants

// Finalize the CRC-32 value by inverting all the bits
crc32 ← crc32 xor 0xFFFFFFFF
return crc32

Related Tags