# Cyclic redundancy check in Python

What is CRC?

CRC or Cyclic Redundancy Check — it is a method of detecting random changes / errors in the communication channel.
CRC uses a generator polynomial that is available on both the sender and receiver sides. An example generator polynomial looks like x ^ 3 + 1. This generator polynomial represents the key 1001. Another example — x ^ 2 + x. this represents key 110.

Example:
Let the data be sent "EVN"
We are converting the string to binary string data.

`` input_string ` ` = ` ` "EVN" ` ` # CONVERT string data to binary string data ` ` data ` ` = ` ` (’` `’ .join (format (ord (x) , ’` ` b’) ` ` for ` ` x ` ` in ` ` input_string)) ` ` print ` ` (data) ``
` OUTPUT: 100010110101101001110`

CRC Key: 10 01
Code: CRC Key Length -1 - & gt; 000 appended at the end of the data.

` New data: 100010110101101001110000 Key: 1001`

We now apply CRC in socket programming on the sender and receiver sides.

Sender side

1. The task is to send the string data to the server / recipient side.
2. The sender sends a string, say "EVN".
3. First, this string is converted to a binary string. The key "100010110101101001110" is known to both the sender and the recipient, here the key is 1001.
4. This data is encoded using a CRC code using a client / sender key.
5. This encoded data is sent to the recipient.
6. The receiver later decodes the encoded data string to check if there was any error or not.

```# 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(divident, divisor):

# Number of bits to be XORed at a time.
pick = len(divisor)

# Slicing the divident to appropriate
# length for particular step
tmp = divident[0 : pick]

while pick < len(divident):

if tmp == ’1’:

# replace the divident by the result
# of XOR and pull 1 bit down
tmp = xor(divisor, tmp) + divident[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) + divident[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 == ’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

# close the connection
s.close()

```

2. The receiver decodes the data using the key and finds out the remainder.
3. If the remainder is zero, it means that there are no errors in the data sent by the sender to the recipient.
4. If the remainder turns out to be non-zero, it means that an error has occurred, a negative acknowledgment is sent to the sender. The sender then resends the data until the receiver receives the correct data.

```# First of all import the socket library
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(divident, divisor):

# Number of bits to be XORed at a time.
pick = len(divisor)

# Slicing the divident to appropriate
# length for particular step
tmp = divident[0: pick]

while pick < len(divident):

if tmp == ’1’:

# replace the divident by the result
# of XOR and pull 1 bit down
tmp = xor(divisor, tmp) + divident[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) + divident[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 == ’1’:
tmp = xor(divisor, tmp)
else:
tmp = xor(’0’*pick, tmp)

checkword = tmp
return checkword

# Function used at the receiver side to decode

def decodeData(data, key):

l_key = len(key)

# Appends n-1 zeroes at end of data
appended_data = data.decode() + ’0’*(l_key-1)
remainder = mod2div(appended_data, key)

return remainder

# Creating Socket
s = socket.socket()
print("Socket successfully created")

# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345

s.bind((’’, port))
print("socket binded to %s" % (port))
# put the socket into listening mode
s.listen(5)
print("socket is listening")

while True:
# Establish connection with client.

# Get data from client
data = c.recv(1024)

print("Received encoded data in binary format :", data.decode())

if not data:
break

key = "1001"

ans = decodeData(data, key)
print("Remainder after decoding is->"+ans)

# If remainder is all zeros then no error occured
temp = "0" * (len(key) - 1)
if ans == temp:
c.sendto(("THANK you Data ->"+data.decode() +
" Received No error FOUND").encode(), (’127.0.0.1’, 12345))
else:
c.sendto(("Error in data").encode(), (’127.0.0.1’, 12345))

c.close()

```

To detect errors in digital data CRC is used, this is a good technique in detecting transmission errors. This technique mainly applies binary division.

In this technique, cyclic redundancy check bits are present, which is a sequence of redundant bits, these bits are appended to the end of the data unit so that the resulting data unit becomes exactly divisible by one second which is a predetermined binary number. .
On the destination side, the input data is divided by the same number, if there is no remainder, the data is assumed to be correct and ready to accept.

A remainder indicates that something happened during the transition, the data drive was corrupted. Therefore, this data drive is not supported.

## Compute CRC of file in Python

Syntax:

```import zlib
zlib.crc32(data[, value])
```

Options:
data - data in bytes,
value - the initial value of the checksum.

Return value:
32-bit integer.

Description:
The crc32() function of the zlib module calculates the CRC (Cyclic Redundancy Check) data checksum. The result is a 32-bit unsigned integer.

If value is present, then it is used as the initial checksum value, otherwise the default value of 0 is used. Passing a value allows the current checksum to be calculated from the concatenation of multiple inputs.

The algorithm is not cryptographically strong and should not be used for authentication or digital signatures. Because the algorithm is intended to be used as a checksum algorithm, it is not suitable for use as a general hashing algorithm.

## Shop Learn programming in R: courses

\$FREE Best Python online courses for 2022

\$FREE Best laptop for Fortnite

\$399+ Best laptop for Excel

\$ Best laptop for Solidworks

\$399+ Best laptop for Roblox

\$399+ Best computer for crypto mining

\$499+ Best laptop for Sims 4

\$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

PythonStackOverflow

Check if one list is a subset of another in Python

PythonStackOverflow

How to specify multiple return types using type-hints

PythonStackOverflow

Printing words vertically in Python

PythonStackOverflow

Python Extract words from a given string

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

PythonStackOverflow

Python os.path.join () method

PythonStackOverflow

Flake8: Ignore specific warning for entire file

## Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries