Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is binascii.crc32 in Python?

Sarvech Qadir

The binascii is a widely used Python library for ASCII-encoded binary representations. It contains several methods for converting to binary from ASCII or hex, and vice versa.

binascii.crc32 computes CRC-32 on binary text data. By definition, CRC-32 refers to the 32-bit checksum of any piece of data. This method is used to compute 32-bit checksum of provided data.

This algorithm is not a general hash algorithm. It should only be used as a checksum algorithm.

Syntax

binascii.crc32(data[, value])
  1. data: The data for which checksum is supposed to be calculated.
  2. value: This is an optional parameter. It is often used where an initial checksum is supposed to be used in the final checksum calculation. By default, it is set to 0.

Code

The following is a basic coding example illustrating the use of binascii.crc32 module:

import binascii

# example from illustration
print(binascii.crc32(bytes("123456789", 'utf-8')))


text = "Welcome to Educative"

# convert to binary data 
text_bytes = bytes(text,'utf-8')

print(binascii.crc32(text_bytes))

# using the value parameter. Since it is zero, the output
# should be same as above.  
print(binascii.crc32(text_bytes, 0))

# Now let's try it in two parts. In the end, the output will 
# be the same. 

print("doing two parts")
# first computing hello
text1 = "Welcome"
text1_bytes = bytes(text1,'utf-8') #converting string to bytes
text1_crc = binascii.crc32(text1_bytes)

print("Welcome" , text1_crc)

text2 = " to Educative"
text2_bytes = bytes(text2,'utf-8')

# now we ll use the above checksum as value parameter.
text2_crc = binascii.crc32(text2_bytes, text1_crc)
print("Welcome to Educative", text2_crc)

# The final output is the same. 

RELATED TAGS

python

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring