bit stuffing program in c.

bit stuffing program in c.

What is bit stuffing program in c

Bit stuffing is a technique used in data communication to ensure data integrity and synchronization between sender and receiver. In this technique, special control characters (known as flags) are used to mark the start and end of a data frame, and if these flags appear within the data frame, they are "stuffed" with additional bits to distinguish them from the flags that mark the start and end of the frame.

bit stuffing program in c

Here's an example program in C that implements bit stuffing:

#include <stdio.h>

#include <string.h>

#define FLAG 0x7E

#define ESCAPE 0x7D

int main()

    unsigned char input[50], output[100];

    int input_len, output_len, i, j, count;

    printf("Enter the data to be stuffed: ");

    scanf("%s", input);

    input_len = strlen((const char*)input);

    output_len = 0;

    count = 0;

    // Add flag characters at the beginning and end of the frame

    output[output_len++] = FLAG;

    for (i = 0; i < input_len; i++) {

        // Check for flag or escape characters

        if (input[i] == FLAG || input[i] == ESCAPE) {

            // Escape the character by adding an escape character and flipping the sixth bit

            output[output_len++] = ESCAPE;

            output[output_len++] = input[i] ^ 0x20;

            count = 0;

        } else {

            output[output_len++] = input[i];

            // Increment count for consecutive 1's

            if (input[i] == '1') {

                count++;

            } else {

                count = 0;

            }

            // Stuff a 0 bit after five consecutive 1's

            if (count == 5) {

                output[output_len++] = '0';

                count = 0;

            }

        }

    }

    // Add flag character at the end of the frame

    output[output_len++] = FLAG;

    printf("Stuffed data: ");

    for (j = 0; j < output_len; j++) {

        printf("%02X ", output[j]);

    }

    printf("\n");

    return 0;

}

In this program, the user is prompted to enter the data to be stuffed, which is then processed and bit-stuffed using the following rules:

  • A flag character (0x7E) is added at the beginning and end of the fram
  • If a flag or escape character (0x7D) is encountered in the data, it is escaped by adding an escape character (0x7D) and flipping the sixth bit
  • If five consecutive 1 bits are encountered in the data, a 0 bit is stuffed after them
  • The stuffed data is stored in an output buffer and printed to the console

Note that in this program, the input data is assumed to be a string of ASCII characters. If the input data is in binary form, it will need to be processed byte by byte instead of character by character.