Skip to content

Instantly share code, notes, and snippets.

@sadn1ck
Last active October 29, 2021 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadn1ck/551cd1d01795abc114dd3b54852f54f7 to your computer and use it in GitHub Desktop.
Save sadn1ck/551cd1d01795abc114dd3b54852f54f7 to your computer and use it in GitHub Desktop.
Gist to calculate CRC of an input polynomial in bit-string format using modulo-2-division
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 modulo_2_division(divident, divisor):
itr = len(divisor)
tmp = divident[0: itr]
while itr < len(divident):
if tmp[0] == '1':
tmp = xor(divisor, tmp) + divident[itr]
else:
tmp = xor('0'*itr, tmp) + divident[itr]
itr += 1
if tmp[0] == '1':
tmp = xor(divisor, tmp)
else:
tmp = xor('0'*itr, tmp)
checkword = tmp
return checkword
def encodeData(data, key):
l_key = len(key)
zero_appended_data = data + '0'*(l_key-1)
remainder = modulo_2_division(zero_appended_data, key)
codeword = data + remainder
print("Input Data : ", data)
print("Remainder : ", remainder)
print("Encoded Data: ", codeword, f" = '{data}' + '{remainder}'")
# Driver code
data = ["11000010", "1010"]
key = ["100011101", "1101"]
for i in range(len(data)):
print("------------------------------")
print(f"Dataset {i+1}")
print("------------------------------")
encodeData(data[i], key[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment