You are on page 1of 3

Computer Networks(3161007)

Experiment-4
Date: 01/02/2022
Aim: Write a program to implement bit stuffing & Destuffing
Apparatus (Software): Turbo C, C++.
Code:
#include <stdio.h>
#include <string.h>

// Function for bit stuffing


void bitStuffing(int N, int arr[])
{
// Stores the stuffed array
int brr[30];

// Variables to traverse arrays


int i, j, k;
i = 0;
j = 0;

// Stores the count of consecutive ones


int count = 1;

// Loop to traverse in the range [0, N]


while (i < N)
{
// If the current bit is a set bit
if (arr[i] == 1)
{
// Insert into array brr[]
brr[j] = arr[i];

// Loop to check for next 5 bits


for (k = i + 1; arr[k] == 1&& k < N&& count < 5; k++)
{
j++;
brr[j] = arr[k];
count++;

// If 5 consecutive set bits are found insert a 0 bit


if (count == 5)
{
j++;
brr[j] = 0;
}
i = k;

190170111090_Mihir Patel
Computer Networks(3161007)

}
}

// Otherwise insert arr[i] into brr[]


else
{
brr[j] = arr[i];
}
i++;
j++;
}

// Print Result
printf("\nStuffed output:");
for (i = 0; i < j; i++)
printf("%d", brr[i]);
}

// Function for bit de-stuffing


void bitDestuffing(int N, int crr[])
{
// Stores the de-stuffed array
int brr[30];

// Variables to traverse the arrays


int i, j, k;
i = 0;
j = 0;

// Stores the count of consecutive ones


int count = 1;

// Loop to traverse in the range [0, N]


while (i < N)
{
// If the current bit is a set bit
if (crr[i] == 1)
{
// Insert into array brr[]
brr[j] = crr[i];

// Loop to check for the next 5 bits


for (k = i + 1; crr[k] == 1&& k < N&& count < 5; k++)
{
j++;
brr[j] = crr[k];
count++;

190170111090_Mihir Patel
Computer Networks(3161007)

// If 5 consecutive set bits are found skip the next bit in crr[]
if (count == 5)
{
k++;
}
i = k;
}
}
// Otherwise insert crr[i] into brr[]
else
{
brr[j] = crr[i];
}
i++;
j++;
}

// Print Result
printf("\nDestuffed output:");
for (i = 0; i < j; i++)
printf("%d", brr[i]);
}

// Driver Code
int main()
{
int N = 10;
int i;
int arr[] = { 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 };
int crr[] = { 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1};

printf("Input bit stream:");


for (i=0; i< N;i++)
printf("%d", arr[i]);

bitStuffing(N, arr);
bitDestuffing(N, crr);

return 0;
}

Output:

190170111090_Mihir Patel

You might also like