DEV Community

GTU Hero
GTU Hero

Posted on

CRC Error Detection in Python: Modulo 2 Division Traced Bit by Bit for GTU Computer Networks

Every Computer Networks syllabus has a data link layer unit, and inside it sits one numerical that shows up again and again: "Calculate the CRC for the given data and generator, and show the transmitted frame." It looks scary because of the polynomial notation, but the whole thing is just XOR done in a loop. In this post we write a tiny CRC encoder and checker in Python, trace it, and then do the same thing by hand the way an exam answer expects.

Disclosure: GTU Hero is my project (link at the end). The code below is my own practice implementation and the output shown is copied from an actual run.

What CRC is actually doing

Sender and receiver agree on a generator polynomial G(x). The sender treats the data bits as a polynomial M(x), appends r zero bits (where r is the degree of G), divides by G using modulo 2 arithmetic, and sticks the remainder onto the end of the data. The resulting frame is exactly divisible by G. The receiver divides the received frame by G again. Remainder zero means "probably fine", anything else means "corrupted".

Modulo 2 arithmetic has no carries and no borrows. Addition and subtraction are both XOR:

0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
Enter fullscreen mode Exit fullscreen mode

That single fact is why the division is simple enough to code in fifteen lines.

The worked problem

Data: 1101011011
Generator: G(x) = x^4 + x + 1, which as bits is 10011

The degree of G is 4, so we append four zeros:

1101011011 0000
Enter fullscreen mode Exit fullscreen mode

The code

def mod2_div(dividend: str, divisor: str, trace=False) -> str:
    bits = list(dividend)
    n = len(divisor)
    for i in range(len(bits) - n + 1):
        if bits[i] == '1':
            for j in range(n):
                bits[i + j] = '0' if bits[i + j] == divisor[j] else '1'
            if trace:
                print(f"step {i:2d}: {''.join(bits)}")
    return ''.join(bits[-(n - 1):])

def crc_encode(data: str, gen: str) -> str:
    padded = data + '0' * (len(gen) - 1)
    rem = mod2_div(padded, gen, trace=True)
    return data + rem

def crc_check(frame: str, gen: str) -> bool:
    return set(mod2_div(frame, gen)) == {'0'}

data, gen = "1101011011", "10011"
frame = crc_encode(data, gen)
print("transmitted:", frame)
print("clean frame ok?", crc_check(frame, gen))
bad = frame[:3] + ('0' if frame[3] == '1' else '1') + frame[4:]
print("corrupted  :", bad)
print("corrupted ok?", crc_check(bad, gen))
Enter fullscreen mode Exit fullscreen mode

The key idea in mod2_div: walk from left to right, and whenever the current leading bit is 1, XOR the generator into the bits starting at that position. If the leading bit is 0, you skip (in long division terms, you "subtract" 00000). At the end, the last r bits are the remainder.

The output

step  0: 01001110110000
step  1: 00000010110000
step  6: 00000000101000
step  8: 00000000001110
transmitted: 11010110111110
clean frame ok? True
corrupted  : 11000110111110
corrupted ok? False
Enter fullscreen mode Exit fullscreen mode

Only four XOR steps were needed, at positions 0, 1, 6 and 8. Everywhere else the leading bit was already 0, so nothing happened. The remainder is the last four bits: 1110.

Transmitted frame = data + remainder = 1101011011 + 1110 = 11010110111110.

Doing it by hand (what you write in the paper)

In the exam you do not get Python, so here is the same division in the long division layout. Each line XORs the generator under the current leading 1, then brings down bits.

11010110110000
10011                 XOR at position 0
-----
 10011                result 01001, bring down the next bit
 10011                XOR at position 1
 -----
 00000                result 00000, next leading 1 is at position 6
      10110           bits 6 to 10
      10011           XOR at position 6
      -----
        10100         result 00101, bring down two bits
        10011         XOR at position 8
        -----
          1110        remainder (last 4 bits)
Enter fullscreen mode Exit fullscreen mode

If you lose track, use the trace from the code as a checking tool: after each XOR the leading 1s disappear one by one, and the positions where XOR happened (0, 1, 6, 8) must match your hand work.

Checking at the receiver

The receiver runs the same division on the full 14 bit frame 11010110111110 with 10011. The remainder comes out 0000, so the frame is accepted. In the code, I flipped bit 3 to simulate noise. The remainder is no longer zero, so crc_check returns False and the frame is rejected.

Why this generator catches errors

A few properties are worth writing as theory points, because GTU questions often ask "what kind of errors can CRC detect":

  • If G(x) has more than one term, every single bit error is detected.
  • If G(x) contains the factor (x + 1), every error with an odd number of flipped bits is detected.
  • A generator of degree r detects every burst error of length r or less.

Our G(x) = x^4 + x + 1 has degree 4, so any burst of 4 or fewer consecutive corrupted bits is caught. That is a good line to add at the end of a numerical answer.

Common mistakes

  1. Forgetting to append zeros. The number of zeros is the degree of G, which is one less than the number of generator bits. Five bit generator, four zeros.
  2. Using normal subtraction. There is no borrow. 0 minus 1 is 1, because it is XOR.
  3. Wrong remainder length. The remainder always has r bits. If you get 110, write it as 0110 with the leading zero.
  4. Appending zeros at the receiver. The receiver divides the received frame as it is. No extra zeros.

Try it yourself

Change data to 1001 and gen to 1011 (that is x^3 + x + 1) and predict the remainder before running. Then try a burst error of 3 bits and confirm it is detected. Once the hand method feels automatic, open real previous year questions: the GTU Hero computer networks papers page lists 10 papers for subject code 3161007, Winter 2021 to Summer 2026, and the data link layer questions there are good timed practice for exactly this kind of trace.

Top comments (0)