Bit Stuffing Code Implementation in Java
This is an implementation of the Bit Stuffing popularly used in data communication, also known as one of the concepts of Framing data bits. To know more please click here.
Sample Output:
This is a sample output with data binary data entered as 11001111110. |
Program Code:
import java.util.*; public class BitStuffing { public static void main(String[] args) { System.out.print("Enter the Binary message: "); Scanner sn=new Scanner(System.in); String data = sn.nextLine(); String res = new String(); String out=new String(); int counter = 0; for(int i=0;i<data.length();i++) { if (data.charAt(i)!='1' && data.charAt(i)!='0') { System.out.println("Enter only Binary values!!!"); return; } if(data.charAt(i) == '1') { counter++; res = res + data.charAt(i); } else { res = res + data.charAt(i); counter = 0; } if(counter == 5) { res = res + '0'; counter = 0; } } String inc="01111110"+res+"01111110"; System.out.println("The Message to be transfered: " +inc); System.out.println("Sending Message...."); counter=0; for(int i=0;i<res.length();i++) { if(res.charAt(i) == '1') { counter++; out = out + res.charAt(i); } else { out = out + res.charAt(i); counter = 0; } if(counter == 5) { if((i+2)!=res.length()) out = out + res.charAt(i+2); else out=out + '1'; i=i+2; counter = 1; } } System.out.println("Message Received...Successfully!!!"); System.out.println("The Destuffed Message is: "+out); } }
Description:
Data Entered is : 11001111110
Flag : 01111110
So basically we look for six consecutive 1's in our data and stuff or insert a "0" after five 1's to distinguish the data from the flag.
While transmitting we insert the flag at both starting and beginning.
At the Receiver's side, we have to destuff our encoded message.
Hence we discard the flag and the stuffed "0" to get our original data.
Comments
Post a Comment