Last active
October 29, 2021 11:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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