This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrc
executable file
·78 lines (59 loc) · 2.26 KB
/
crc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
from math import log, ceil
def print_help():
print("""
Script to generate Cyclic Redundancy Check codeword for
Networks and Internet Systems.
# Usage: `$ ./crc`
""")
def getCRC(dataword, generator):
dword = int(dataword, 2)
l_gen = len(generator)
# append 0s to dividend
dividend = dword << (l_gen - 1)
dividend = divMod2(dividend, generator)
# finally, AND the initial dividend with the remainder (=dividend)
codeword = dword if not dividend else (dword << (l_gen-1) | dividend)
print("CRC:\t\t\t", bin(dividend).lstrip("-0b").zfill(l_gen-1))
print("Codeword:\t\t", bin(codeword).lstrip("-0b"))
def divMod2(dividend, generator):
l_gen = len(generator)
# shift specifies the no. of least significant bits not being XORed
shift = ceil(log(dividend + 1, 2)) - l_gen
# ceil(log(dividend+1 , 2)) is the no. of binary
# digits in dividend
generator = int(generator, 2)
while dividend >= generator or shift >= 0:
# bitwise XOR the MSBs of dividend with generator
# replace the operated MSBs from the dividend with
# remainder generated
rem = (dividend >> shift) ^ generator
dividend = (dividend & ((1 << shift) - 1)) | (rem << shift)
# change shift variable
shift = ceil(log(dividend+1, 2)) - l_gen
return dividend
def hasError(message, generator):
msg = int(message, 2)
l_gen = len(generator)
r = divMod2(msg, generator)
remainder = bin(r).lstrip("-0b").zfill(l_gen-1)
print("Remainder:\t\t", remainder if remainder else None)
return r != 0
if __name__ == '__main__':
try:
op = int(input("1. Find k-1 bit CRC for k bit generator\n" +
"2. Check if data received has error\n" +
"Choose 1 or 2:\t\t "))
if op == 1:
dataword = input("\nMessage data:\t\t ")
generator = input("Generator:\t\t ")
getCRC(dataword, generator)
elif op == 2:
received = input("\nMessage received:\t ")
generator = input("Generator:\t\t ")
print("Error:\t\t\t", hasError(received, generator))
else:
print("Wrong input!")
except Exception as e:
print(e)
print_help()