CN-LAB-V-SEM

Exercise 12: Implement Byte Stuffing Framing Method to Resolve Framing Errors

Byte Stuffing Program

#include <stdio.h>
#include <string.h>

int main() {
    char inp[50], stuffed[100], flag[] = "flag", esc[] = "esc";
    int len, i, j = 0;

    printf("Enter length of string: ");
    scanf("%d", &len);

    printf("Enter the string: ");
    scanf("%s", inp);

    printf("You Entered: %s\n", inp);

    strcpy(stuffed, flag);
    j += strlen(flag);

    for (i = 0; i < len; i++) {
        if (inp[i] == 'f' && strncmp(&inp[i], "flag", 4) == 0) {
            strcpy(&stuffed[j], esc);
            j += strlen(esc);
        }
        stuffed[j++] = inp[i];
    }

    strcpy(&stuffed[j], flag);
    printf("Byte Stuffing of sender side: %s\n", stuffed);

    return 0;
}

Output Example

Enter length of string: 8
Enter the string: 11000010
You Entered: 11000010
Byte Stuffing of sender side: flag11000010flag

Explanation

This program demonstrates the Byte Stuffing Framing Method, commonly used in communication protocols like HDLC.

Steps

  1. Input: The user enters the length of the data and the data string.
  2. Flags and Escape Sequences:
    • A flag string marks the start and end of the data frame.
    • If the data contains reserved keywords like flag, an esc (escape sequence) is inserted before it to distinguish the data from framing markers.
  3. Byte Stuffing Logic:
    • The program checks for occurrences of flag in the input data and adds an esc sequence before each occurrence.
    • The resulting string includes flag at both ends and stuffed bytes as needed.
  4. Output: The framed data ensures that reserved characters do not interfere with framing, providing a reliable mechanism for transmitting data.

This method is widely used in data communication to avoid ambiguities caused by reserved characters within the data payload.