Cyclic Redundancy Check in Python
Last Updated :
21 Dec, 2022
Prerequisites: Know about Cyclic redundancy, Socket Programming
What is CRC?
CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in the communication channel.
CRC uses Generator Polynomial which is available on both sender and receiver sides. An example generator polynomial is of the form of x^3 + 1. This generator polynomial represents key 1001. Another example is x^2 + x. that represents key 110.
Example:
Let data send is "EVN"
We convert a string to binary string data.
Python
input_string = "EVN"
# CONVERT string data to binary string data
data = (''.join(format(ord(x), 'b') for x in input_string))
print (data)
Output100010110101101001110
CRC KEY: 1001
Code: CRC key length -1 -> 000 appended at end of data.
New data: 100010110101101001110000
Key:1001
Now we apply CRC in socket programming python at both sender and receiver sides.
Sender Side
1. The task is to send string data to the server/receiver side.
2. The sender sends a string let us say "EVN".
3. First, this string is converted to binary string "100010110101101001110" key is known to both the side sender and receiver here key used is 1001.
4. This data is encoded using the CRC code using the key on the client/sender side.
5. This encoded data is sent to the receiver.
6. Receiver later decodes the encoded data string to verify whether there was any error or not.
Python3
# Import socket module
import socket
def xor(a, b):
# initialize result
result = []
# Traverse all bits, if bits are
# same, then XOR is 0, else 1
for i in range(1, len(b)):
if a[i] == b[i]:
result.append('0')
else:
result.append('1')
return ''.join(result)
# Performs Modulo-2 division
def mod2div(dividend, divisor):
# Number of bits to be XORed at a time.
pick = len(divisor)
# Slicing the dividend to appropriate
# length for particular step
tmp = dividend[0 : pick]
while pick < len(dividend):
if tmp[0] == '1':
# replace the dividend by the result
# of XOR and pull 1 bit down
tmp = xor(divisor, tmp) + dividend[pick]
else: # If leftmost bit is '0'
# If the leftmost bit of the dividend (or the
# part used in each step) is 0, the step cannot
# use the regular divisor; we need to use an
# all-0s divisor.
tmp = xor('0'*pick, tmp) + dividend[pick]
# increment pick to move further
pick += 1
# For the last n bits, we have to carry it out
# normally as increased value of pick will cause
# Index Out of Bounds.
if tmp[0] == '1':
tmp = xor(divisor, tmp)
else:
tmp = xor('0'*pick, tmp)
checkword = tmp
return checkword
# Function used at the sender side to encode
# data by appending remainder of modular division
# at the end of data.
def encodeData(data, key):
l_key = len(key)
# Appends n-1 zeroes at end of data
appended_data = data + '0'*(l_key-1)
remainder = mod2div(appended_data, key)
# Append remainder in the original data
codeword = data + remainder
return codeword
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# Send data to server 'Hello world'
## s.sendall('Hello World')
input_string = input("Enter data you want to send->")
#s.sendall(input_string)
data =(''.join(format(ord(x), 'b') for x in input_string))
print("Entered data in binary format :",data)
key = "1001"
ans = encodeData(data,key)
print("Encoded data to be sent to server in binary format :",ans)
s.sendto(ans.encode(),('127.0.0.1', 12345))
# receive data from the server
print("Received feedback from server :",s.recv(1024).decode())
# close the connection
s.close()

Receiver Side
1. The receiver receives the encoded data string from the sender.
2. Receiver with the help of the key decodes the data and finds out the remainder.
3. If the remainder is zero then it means there is no error in data sent by the sender to the receiver.
4. If the remainder comes out to be non-zero it means there was an error, a Negative Acknowledgement is sent to the sender. The sender then resends the data until the receiver receives the correct data.
Python3
# Import socket module
import socket
def xor(a, b):
# initialize result
result = []
# Traverse all bits, if bits are
# same, then XOR is 0, else 1
for i in range(1, len(b)):
if a[i] == b[i]:
result.append('0')
else:
result.append('1')
return ''.join(result)
# Performs Modulo-2 division
def mod2div(dividend, divisor):
# Number of bits to be XORed at a time.
pick = len(divisor)
# Slicing the dividend to appropriate
# length for particular step
tmp = dividend[0 : pick]
while pick < len(dividend):
if tmp[0] == '1':
# replace the dividend by the result
# of XOR and pull 1 bit down
tmp = xor(divisor, tmp) + dividend[pick]
else: # If leftmost bit is '0'
# If the leftmost bit of the dividend (or the
# part used in each step) is 0, the step cannot
# use the regular divisor; we need to use an
# all-0s divisor.
tmp = xor('0'*pick, tmp) + dividend[pick]
# increment pick to move further
pick += 1
# For the last n bits, we have to carry it out
# normally as increased value of pick will cause
# Index Out of Bounds.
if tmp[0] == '1':
tmp = xor(divisor, tmp)
else:
tmp = xor('0'*pick, tmp)
checkword = tmp
return checkword
# Function used at the sender side to encode
# data by appending remainder of modular division
# at the end of data.
def encodeData(data, key):
l_key = len(key)
# Appends n-1 zeroes at end of data
appended_data = data + '0'*(l_key-1)
remainder = mod2div(appended_data, key)
# Append remainder in the original data
codeword = data + remainder
return codeword
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# Send data to server 'Hello world'
## s.sendall('Hello World')
input_string = input("Enter data you want to send->")
#s.sendall(input_string)
data =(''.join(format(ord(x), 'b') for x in input_string))
print("Entered data in binary format :",data)
key = "1001"
ans = encodeData(data,key)
print("Encoded data to be sent to server in binary format :",ans)
s.sendto(ans.encode(),('127.0.0.1', 12345))
# receive data from the server
print("Received feedback from server :",s.recv(1024).decode())
# close the connection
s.close()

NOTE:
How to run the program:
1. You should have a socket programming library.
2. First, run server program then runs client program.
3. Indentation error may occur while you copy-paste the code so be careful while copying.
4. You'll see the following output in your split terminal.

Similar Reads
Check for True or False in Python Python has built-in data types True and False. These boolean values are used to represent truth and false in logical operations, conditional statements, and expressions. In this article, we will see how we can check the value of an expression in Python.Common Ways to Check for True or FalsePython pr
2 min read
Code Golfing in Python Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters "wins". Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language,
8 min read
Check if two lists are identical in Python Our task is to check if two lists are identical or not. By "identical", we mean that the lists contain the same elements in the same order. The simplest way to check if two lists are identical using the equality operator (==).Using Equality Operator (==)The easiest way to check if two lists are iden
2 min read
Truthy in Python In Python Programming, every value is either evaluated as True or False. Any value that is evaluated as a True boolean type is considered Truthy. The bool() function is used to check the Truthy or Falsy of an object. We will check how Python evaluates the truthiness of a value within a conditional s
1 min read
How to check if a Python variable exists? Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Letâs explore different methods to efficiently check if a va
3 min read
Check multiple conditions in if statement - Python If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true. Syntax:if (condition): code1else: code2[on_true] if [expression] else [on_false]Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif
4 min read
Python - Check if list contains all unique elements To check if a list contains all unique elements in Python, we can compare the length of the list with the length of a set created from the list. A set automatically removes duplicates, so if the lengths match, the list contains all unique elements. Python provides several ways to check if all elemen
2 min read
Check if element exists in list in Python In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example:Pythona = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Element exists in the
3 min read
zlib.crc32() in python With the help of zlib.crc32() method, we can compute the checksum for crc32 (Cyclic Redundancy Check) to a particular data. It will give 32-bit integer value as a result by using zlib.crc32() method. Syntax : zlib.crc32(s) Return : Return the unsigned 32-bit checksum integer. Example #1 : In this ex
1 min read
Check if adding an edge makes the Undirected Graph cyclic or not Given an undirected graph, the task is to if adding an edge makes the graph cyclic or not. In an Undirected graph, a cycle is a path of edges that connects a sequence of vertices back to itself. In other words, a cycle is a closed loop of edges that allows you to traverse the graph and return to the
15+ min read