How to calculate the CRC32 of a string in Python

1 Answer

0 votes
import zlib

def crc32_of_string(text: str) -> str:
    """
    Calculates the CRC32 checksum of a string.

    Args:
        text (str): The input string.

    Returns:
        str: The CRC32 value as an 8‑character uppercase hex string.
    """
    # Convert the string to bytes (UTF‑8 is the standard encoding)
    data = text.encode("utf-8")

    # zlib.crc32 returns a signed 32‑bit integer on some systems,
    # so we mask with 0xFFFFFFFF to ensure an unsigned 32‑bit result.
    crc = zlib.crc32(data) & 0xFFFFFFFF

    # Format as 8‑digit uppercase hexadecimal (standard CRC32 format)
    return f"{crc:08X}"



text = "Python Programming"

crc = crc32_of_string(text)

print("CRC32:", crc)


'''
run:

CRC32: EA53455C

'''

 



answered May 8 by avibootz
...