0% found this document useful (0 votes)
4 views20 pages

Bit Stuffing in C Programming Code

The document outlines the implementation of data link layer framing methods, specifically focusing on bit stuffing and character stuffing techniques in C programming. It provides detailed explanations of the code for both methods, including variable declarations, input handling, and the logic for processing the data to prevent confusion with special patterns. Additionally, it includes example runs and outputs for both techniques, demonstrating how the programs function and the expected results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Bit Stuffing in C Programming Code

The document outlines the implementation of data link layer framing methods, specifically focusing on bit stuffing and character stuffing techniques in C programming. It provides detailed explanations of the code for both methods, including variable declarations, input handling, and the logic for processing the data to prevent confusion with special patterns. Additionally, it includes example runs and outputs for both techniques, demonstrating how the programs function and the expected results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Aim:

☛ Implement the data link layer framing methods such as character,


character-stuffing and bit stuffing.

Solution :

Bit Stuffing :

Source Code:

#include<stdio.h>

void main() {
int ip_frame[100], op_frame[200];
int i, j = 0, n;
int count = 0;

printf("Enter frame length: ");


scanf("%d", &n);

printf("Enter input frame (0's and 1's only):\n");


for(i = 0; i < n; i++) {
scanf("%d", &ip_frame[i]);
}

// Bit stuffing logic


for(i = 0; i < n; i++) {
op_frame[j++] = ip_frame[i];

if(ip_frame[i] == 1) {
count++;
if(count == 5) {
op_frame[j++] = 0; // Stuff a 0 after five 1s
count = 0; // Reset count after
stuffing
}
} else {
count = 0; // Reset count if a 0 is found
}
}

printf("\nAfter bit stuffing, the frame is:\n");


for(i = 0; i < j; i++) {
printf("%d", op_frame[i]);
}
printf("\n");
}

Output:

$ gcc bit_stuffing.c
$ ./[Link]
enter frame length: 9
Enter input frame (0's & 1's only) :
0
1
0
1
1
1
1
1
1

After stuffing, the frame is:


0101111101

Sure! Let's go step by step and explain the bit stuffing program in a very simple and beginner-
friendly way. This explanation is especially for those who are new to C programming.

✅ What is Bit Stuffing? (In Simple Words)


Imagine you have a message to send in 0s and 1s. If your system uses a special pattern like
01111110 to mark the start and end of a message, and this pattern accidentally appears inside
your message, it may confuse the receiver.

So, to prevent this:

 If five 1s (11111) appear in a row, we automatically insert a 0 (0) after them.


 This is called bit stuffing.

Later, the receiver will remove these extra 0s while reading the message — this process is
called bit unstuffing.

✅ Code Step by Step with Detailed Explanation


🔹 1. Include Header
c
CopyEdit
#include<stdio.h>

This line tells the compiler to include Standard Input Output functions, like printf() and
scanf().

🔹 2. Main Function
c
CopyEdit
void main() {
This is the starting point of the program. Everything inside { } will run when the program is
executed.

🔹 3. Variable Declaration
c
CopyEdit
int ip_frame[100], op_frame[200];
int i, j = 0, n;
int count = 0;

 ip_frame[100]: array to store the original input bits (maximum 100 bits)
 op_frame[200]: array to store the output bits after bit stuffing (more space needed
since we might insert extra 0s)
 i: for looping through input
 j: for indexing output
 n: number of bits in the input
 count: to count how many 1s in a row

🔹 4. Taking Input
printf("Enter frame length: ");
scanf("%d", &n);

The user enters how many bits are in the input (e.g., 8 bits).

printf("Enter input frame (0's and 1's only):\n");


for(i = 0; i < n; i++) {
scanf("%d", &ip_frame[i]);
}

The user then enters each bit (0 or 1), which is stored in ip_frame[].

For example:
If user inputs: 1 1 1 1 1 0 1 0, it is stored in:

CopyEdit
ip_frame[0] = 1
ip_frame[1] = 1
ip_frame[2] = 1
ip_frame[3] = 1
ip_frame[4] = 1
ip_frame[5] = 0
ip_frame[6] = 1
ip_frame[7] = 0
🔹 5. Bit Stuffing Logic
c
CopyEdit
for(i = 0; i < n; i++) {
op_frame[j++] = ip_frame[i]; // Copy bit to output

if(ip_frame[i] == 1) {
count++; // Increase count of 1s
if(count == 5) {
op_frame[j++] = 0; // Stuff a 0 after five 1s
count = 0; // Reset the count
}
} else {
count = 0; // If current bit is 0, reset the count
}
}

Let’s break it down:

1. op_frame[j++] = ip_frame[i];
→ Copy the current bit from input to output.
2. if(ip_frame[i] == 1)
→ If the bit is 1, increase the count.
3. if(count == 5)
→ If there are 5 consecutive 1s, add a 0 in output (this is stuffing).
4. count = 0
→ After stuffing, reset the counter.
5. else count = 0
→ If the bit is 0, we reset the count since the streak of 1s is broken.

🔹 6. Display Output
c
CopyEdit
printf("\nAfter bit stuffing, the frame is:\n");
for(i = 0; i < j; i++) {
printf("%d", op_frame[i]);
}
printf("\n");
}

This part prints the final output bit-by-bit, all in a single line.
🧪 Example Run
Input:
yaml
CopyEdit
Enter frame length: 8
Enter input frame:
1 1 1 1 1 1 0 1

Working:

 First five 1s → 11111 → then stuff a 0


 Sixth bit is 1 → 1
 Next bits: 0 1

Final output:
CopyEdit
1111100101

The 0 after 5 ones is stuffed.

✅ Summary
Concept Meaning
Bit Stuffing Insert 0 after five 1s to avoid special patterns in data
Why? To avoid confusion with flags used to mark start/end of frames
How? Count consecutive 1s, stuff 0 after 5 of them
This Program Reads bits, processes them, outputs stuffed frame

2) explain the above program with step by step explanation in easy understanding way for beginners in c

ChatGPT said:

Absolutely! Let's break down your character stuffing program step by step in a way that's easy
for beginners in C programming to understand. We’ll walk through what each line does and
how it works with simple terms, examples, and why each part is needed.
🧠 What is the Goal of This Program?
This program performs character stuffing, a technique used in data communication. It:

1. Takes a string (like a message).


2. Adds a start delimiter (dlestx) and an end delimiter (dleetx) to show where the
message begins and ends.
3. Inserts a specific character into the string at a position given by the user.
4. Wraps that inserted character with dle to mark it as stuffed.
5. Escapes any dle in the original string to prevent confusion.

✅ Step-by-Step Code Explanation

🔹 Step 1: Include Header Files


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

 stdio.h: lets you use printf, scanf, etc.


 string.h: gives you the strlen() function to get the length of a string.

🔹 Step 2: Start the Program


c
CopyEdit
void main()

 main() is where your program starts.


 void means this function doesn't return any value.

🔹 Step 3: Declare Variables


c
CopyEdit
int i = 0, j = 0, n, pos;
char a[20], b[100], ch;

 a[20]: to store the input string (up to 19 characters + \0)


 b[100]: to store the output (stuffed) frame
 ch: character to stuff
 pos: position where you want to insert the new character
 i, j: counters for input and output arrays

🔹 Step 4: Take Input String


c
CopyEdit
printf("Enter the string:\n");
scanf("%s", a);
n = strlen(a);

 Asks the user to enter a string (no spaces allowed with scanf("%s"))
 n = strlen(a) stores the length of the string

📌 Example:
If user enters hello,
a = "hello" and n = 5

🔹 Step 5: Ask for Position to Insert Character


c
CopyEdit
printf("Enter position to insert the character:\n");
scanf("%d", &pos);

 User enters a position (e.g., 3) — positions are 1-based.

Then we check if it's valid:

c
CopyEdit
while(pos < 1 || pos > n + 1)
{
printf("Invalid position, enter again: ");
scanf("%d", &pos);
}

 Valid positions are from 1 to n + 1 (you can insert after the last character)
🔹 Step 6: Ask for Character to Insert
c
CopyEdit
getchar(); // Clear the newline character
printf("Enter the character to stuff:\n");
ch = getchar();

 getchar() is used to read the character after position input


 It reads even special characters like #, @, etc.

🔹 Step 7: Add Starting Delimiter to Output Frame


c
CopyEdit
b[0] = 'd'; b[1] = 'l'; b[2] = 'e'; b[3] = 's'; b[4] = 't'; b[5] = 'x';
j = 6;

 Adds "dlestx" to the start of b[]


 j is the current index in output array, starts at 6

This marks: Start of message

🔹 Step 8: Process Input String with Loop


c
CopyEdit
for (i = 0; i < n; i++)

Loops through each character in the input string.

📌 8.1. Check for Stuffing Position


c
CopyEdit
if (i == pos - 1)
{
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e';
b[j++] = ch;
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e';
}

 When the loop reaches the position to insert the character:


o Insert dle, then the character, then another dle
o This helps the receiver identify the inserted character

📌 8.2. Escape Original dle Sequences


c
CopyEdit
if (a[i] == 'd' && a[i + 1] == 'l' && a[i + 2] == 'e')
{
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e';
}

 If your original input contains "dle" (like abcdleef), it might confuse the receiver.
 So we add an extra dle before it to escape it.

📌 8.3. Copy the Input Character


c
CopyEdit
b[j++] = a[i];

 This copies each character from the original string to the output array.

🔹 Step 9: If Stuffing is at the End


c
CopyEdit
if (pos == n + 1)
{
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e';
b[j++] = ch;
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e';
}

If the position to insert is after the last character, then insert the character at the end.

🔹 Step 10: Add Ending Delimiter


c
CopyEdit
b[j++] = 'd'; b[j++] = 'l'; b[j++] = 'e'; b[j++] = 'e'; b[j++] = 't'; b[j++] =
'x';
b[j] = '\0';

 Adds "dleetx" to signal end of frame


 \0 marks the end of the string in C

🔹 Step 11: Print Final Stuffed Frame


c
CopyEdit
printf("\nFrame after stuffing:\n%s\n", b);

Displays the full stuffed frame.

🧪 Example Output
Input:
sql
CopyEdit
Enter the string:
hello
Enter position to insert the character:
3
Enter the character to stuff:
X

Processing:

 Original: hello
 Insert X at position 3 → after h and e
 Add start: dlestx
 Insert dleXdle at position 3
 Add end: dleetx

Final Output:
nginx
CopyEdit
dlestxhedleXdlello dleetx

✅ Summary
Part Purpose

dlestx Marks start of message


Part Purpose

Inserted dle + ch + dle Stuffed character with delimiters

Escape dle in data Prevents confusion if original message contains dle

dleetx Marks end of message

Output Stuffed frame ready for transmission

Would you like me to help you write the reverse program (to remove stuffed characters and
delimiter

Output:

$ gcc char_stuffing.c
$ ./[Link]
Enter the string:
madhu
Enter position to insert the character:
2
Enter the character to stuff:
k

Frame after stuffing:


dlestxmdlekdleadhudleetx

3) File Name: char_count.c

#include<stdio.h>
#include<string.h>
char data[20][20];
int n;

int main() {
int i, j, ch;
char tmp[20][30]; // Stores frames with character count

printf("Enter the number of frames: ");


scanf("%d", &n);
getchar(); // clear newline after scanf

// Input the frames


for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
fgets(data[i], sizeof(data[i]), stdin);
data[i][strcspn(data[i], "\n")] = '\0'; // remove
newline
}

// Creating frames with count prefix


for (i = 1; i <= n; i++) {
int len = strlen(data[i]);
tmp[i][0] = len + '0'; // store count as char (e.g.,
'5')
tmp[i][1] = '\0';
strcat(tmp[i], data[i]); // append actual data after
count
}

// AT THE SENDER
printf("\n\t\tAT THE SENDER:\n");
printf("Data as frames:\n");
for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
puts(tmp[i]);
}

printf("Data transmitted: ");


for (i = 1; i <= n; i++) {
printf("%s", tmp[i]);
}

// AT THE RECEIVER
printf("\n\n\t\tAT THE RECEIVER:\n");
printf("The data received: ");

for (i = 1; i <= n; i++) {


ch = tmp[i][0] - '0'; // get count
for (j = 0; j < ch; j++) {
data[i][j] = tmp[i][j + 1]; // skip count character
}
data[i][j] = '\0'; // null terminate
}

printf("\nData after removing count characters: ");


for (i = 1; i <= n; i++) {
printf("%s", data[i]);
}

printf("\n\nData in frame form:\n");


for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
puts(data[i]);
}

return 0;
}

Output:

$ gcc char_count.c
$ ./[Link]
Enter the number of frames: 3
Frame 1: Computer
Frame 2: Networks
Frame 3: Lab

AT THE SENDER:
Data as frames:
Frame 1: 8Computer
Frame 2: 8Networks
Frame 3: 3Lab
Data transmitted: 8Computer8Networks3Lab

AT THE RECEIVER:
The data received:
Data after removing count characters: ComputerNetworksLab

Data in frame form:


Frame 1: Computer
Frame 2: Networks
Frame 3: Lab

✅ What is the Program About?


It simulates a communication system:

1. Sender:
o Takes multiple strings (called frames).
o Adds the length (count) of each frame at the beginning of the string.
o Sends the frames together as one message.
2. Receiver:
o Receives the long message.
o Uses the count at the beginning of each frame to extract the original data.
o Displays the data frame by frame.

🧠 What is Character Count Framing?


Character count framing means:
You send each frame with its length in characters placed at the front.

🔹 Example:
Frame: hello → 5 characters → Transmitted as: 5hello

The receiver reads 5, and knows the next 5 letters are part of that frame.
🔍 Step-by-Step Code Explanation

🔸 Step 1: Header and Global Variables


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

char data[20][20]; // To store up to 20 strings (each up to 19 characters)


int n; // Number of frames

 stdio.h → for input/output functions like printf() and scanf()


 string.h → for string handling like strlen()
 data[][] → stores input strings (frames)
 n → number of frames entered by user

🔸 Step 2: Main Function and Temporary Array


c
CopyEdit
int main() {
int i, j, ch;
char tmp[20][30]; // To store frames with count prefix

 tmp[][] → stores modified frames, where the first character is the count and the rest is
the string.

🔸 Step 3: Input Number of Frames


c
CopyEdit
printf("Enter the number of frames: ");
scanf("%d", &n);
getchar(); // Clears the newline character left in input buffer

 User enters how many frames they want to send.


 getchar() clears the newline left after scanf so that the next fgets() works properly.

🔸 Step 4: Input Each Frame (String)


c
CopyEdit
for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
fgets(data[i], sizeof(data[i]), stdin);
data[i][strcspn(data[i], "\n")] = '\0'; // remove newline
}

 Loop runs from 1 to n, taking input for each frame.


 fgets() is used so the user can type strings with spaces (unlike scanf("%s")).
 The last line removes the newline character from the input.

📌 Example input:

yaml
CopyEdit
Frame 1: hello
Frame 2: how are
Frame 3: you

🔸 Step 5: Add Character Count to Each Frame


c
CopyEdit
for (i = 1; i <= n; i++) {
int len = strlen(data[i]); // Length of the string
tmp[i][0] = len + '0'; // Convert length to a character
tmp[i][1] = '\0'; // Null-terminate the string
strcat(tmp[i], data[i]); // Add actual data after count
}

 strlen() finds the number of characters in the string.


 len + '0' converts integer len to a character.
o For example, 5 + '0' = '5'
 strcat() joins the count character and the data string.

📌 Example:

go
CopyEdit
data[1] = "hello" → len = 5
tmp[1] = "5hello"

🔸 Step 6: Print Frames at the Sender


c
CopyEdit
printf("\n\t\tAT THE SENDER:\n");
printf("Data as frames:\n");
for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
puts(tmp[i]);
}

 Shows each frame with its count.

Then:

c
CopyEdit
printf("Data transmitted: ");
for (i = 1; i <= n; i++) {
printf("%s", tmp[i]);
}

 Combines all the frames into one continuous message (like how data is sent over a
network).

📌 Example output:

yaml
CopyEdit
Frame 1: 5hello
Frame 2: 7how are
Frame 3: 3you
Data transmitted: 5hello7how are3you

🔸 Step 7: At the Receiver – Extracting Data


c
CopyEdit
printf("\n\n\t\tAT THE RECEIVER:\n");
printf("The data received: ");

This part reconstructs the original data from the count-framed message:

c
CopyEdit
for (i = 1; i <= n; i++) {
ch = tmp[i][0] - '0'; // Convert count character to number
for (j = 0; j < ch; j++) {
data[i][j] = tmp[i][j + 1]; // Copy original data (skip count)
}
data[i][j] = '\0'; // Null-terminate the string
}

 tmp[i][0] is the count character (e.g., '5')


 '5' - '0' gives 5 (integer)
 Then the next 5 characters are copied to data[i]

🔸 Step 8: Show Received Data


c
CopyEdit
printf("\nData after removing count characters: ");
for (i = 1; i <= n; i++) {
printf("%s", data[i]);
}

 Prints all the recovered data as one combined string.

c
CopyEdit
printf("\n\nData in frame form:\n");
for (i = 1; i <= n; i++) {
printf("Frame %d: ", i);
puts(data[i]);
}

 Shows each frame separately (like at the sender).

🧪 Example Full Execution


Input:
yaml
CopyEdit
Enter the number of frames: 3
Frame 1: hello
Frame 2: how
Frame 3: you

Output:
yaml
CopyEdit
AT THE SENDER:
Data as frames:
Frame 1: 5hello
Frame 2: 3how
Frame 3: 3you
Data transmitted: 5hello3how3you

AT THE RECEIVER:
The data received:
Data after removing count characters: hellohowyou

Data in frame form:


Frame 1: hello
Frame 2: how
Frame 3: you

🧠 Key Concepts You Learned:


Concept Explanation
Character Count Framing Add the length of data at the start of each frame
strlen() Finds length of a string
'0' + number Converts a number to a character
'character' - '0' Converts character back to a number
fgets() Reads string with spaces
strcat() Joins two strings
data[i][j] = '\0' Ends the string

✅ Suggestions for Beginners:


 Start indexing from 0 (i = 0) instead of 1 for consistency.
 Use atoi() if you want to support multi-digit counts in the future.
 Always check array sizes and boundaries to avoid overflow.

You might also like