Two data link layer techniques from my undergrad Computer Networks lab, written in Python: framing a stream so the receiver knows where each frame starts and ends, and Hamming code so a single flipped bit can be found and fixed.
Byte stuffing. Frames start and end with a flag byte (F). If the data itself contains F or the escape character ~, an escape is put in front of it so it can't be mistaken for a frame boundary.
data: F A ~ F B
frame: F ~F A ~~ ~F B F
Bit stuffing. The flag is 01111110. After every five 1s in a row in the data, a 0 is inserted, so six 1s in a row can only ever mean a flag. The receiver drops any 0 that comes right after five 1s.
data: 111111011111111
frame: 01111110 11111 0 1 0 11111 0 111 01111110
Parity bits go at positions 1, 2, 4, 8, ... and each one covers every position whose binary index has that bit set. For 16 data bits you need 5 parity bits (2^5 >= 16 + 5 + 1).
message: 1101001100110101 (even parity)
parity: P1=0 P2=1 P3=1 P4=1 P5=1
codeword: 011110110011001110101
On the receiving side, recomputing the parity checks gives a syndrome. If it's 0 the codeword is clean; otherwise its value is exactly the position of the flipped bit, so it can be corrected.
python framing.py
python hamming.py
python -m pytest -qBoth are menu-driven, like the lab versions.
The original code only existed inside two Word lab records (still in lab-records/). I pulled it out and rewrote it as plain functions:
- Each function returns its result instead of printing, so it can be tested.
- Verified against the lab records: the tests check that the new code gives exactly the outputs recorded there (
FA~FB,111111011111111and the 16-bit Hamming example). - Fixed a bug: the original Hamming program inserted the parity slots into the message list in place, so choosing even and then odd parity in the same session gave a wrong codeword.
- New: error detection and correction (option 3 in
hamming.py). Tests flip a random bit in hundreds of random codewords and check it's always found and fixed. - New: input checks for non-binary input.