pythoncrc32

Python find CRC32 of string


I tried to get CRC32 of a string data type variable but I'm getting the following error:

>>> message='hello world!'
>>> import binascii
>>> binascii.crc32(message)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

For a string value, it can be done with binascii.crc32(b'hello world!') but I would like to know how to do this for a string data-type variable.


Solution

  • When you are computing crc32 of some data, you need to know the exact value of bytes you are hashing. One string can represent different values of bytes in different encodings, therefore passing string as parameter is ambiguous.

    When using binascii.crc32(b'hello world!'), you are converting char array into array of bytes using simple ascii table as conversion.

    To convert any string, you can use:

    import binascii
    
    text = 'hello'
    binascii.crc32(text.encode('utf8'))