Implementation of Bit Stuffing and Bit Destuffing - GeeksforGeeks

31 Dec, 2021
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1’s. Given an array, arr[] of size N consisting of 0’s and 1’s, the task is to return an array after the bit stuffing.
Examples:
Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecutive 1’s are encountered after the 4th index of the given array. Hence, a zero bit has been inserted into the stuffed array after the 4th index 
Input: N = 6, arr[] = {1, 0, 1, 0, 1, 0}Output: 101010
Approach: The idea is to check if the given array consists of 5 consecutive 1’s. Follow the steps below to solve the problem:
Initialize the array brr[] which stores the stuffed array. Also, create a variable count which maintains the count of the consecutive 1’s.
Traverse in a while loop using a variable i in the range [0, N) and perform the following tasks:If arr[i] is 1 then check for the next 4 bits if they are set bits as well. If they are, then insert a 0 bit after inserting all the 5 set bits into the array brr[].Otherwise, insert the value of arr[i] into the array brr[].
If arr[i] is 1 then check for the next 4 bits if they are set bits as well. If they are, then insert a 0 bit after inserting all the 5 set bits into the array brr[].
Otherwise, insert the value of arr[i] into the array brr[].
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Function for bit stuffingvoid 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;            }        }         // Otherwise insert arr[i] into        // the array brr[]        else        {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for(i = 0; i < j; i++)        cout << brr[i];} // Driver codeint main(){    int N = 6;    int arr[] = { 1, 1, 1, 1, 1, 1 };     bitStuffing(N, arr);;    return 0;} // This code is contributed by target_2
// C program for the above approach#include <stdio.h>#include <string.h> // Function for bit stuffingvoid 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;            }        }         // Otherwise insert arr[i] into        // the array brr[]        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        printf("%d", brr[i]);} // Driver Codeint main(){    int N = 6;    int arr[] = { 1, 1, 1, 1, 1, 1 };     bitStuffing(N, arr);     return 0;}
// Java program for the above approachclass GFG{ // Function for bit stuffingstatic void bitStuffing(int N, int arr[]){       // Stores the stuffed array    int []brr = new int[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; k < N &&                 arr[k] == 1                                   && 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;            }        }         // Otherwise insert arr[i] into        // the array brr[]        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        System.out.printf("%d", brr[i]);} // Driver Codepublic static void main(String[] args){    int N = 6;    int arr[] = { 1, 1, 1, 1, 1, 1 };     bitStuffing(N, arr); }} // This code is contributed by shikhasingrajput
# Python3 program for the above approach # Function for bit stuffingdef bitStuffing(N, arr):         # Stores the stuffed array    brr = [0 for _ in range(30)]     # Variables to traverse arrays    k = 0    i = 0    j = 0     # Stores the count of consecutive ones    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            k = i + 1            while True:                if not (k < N and arr[k] == 1 and                        count < 5):                    break                 j += 1                brr[j] = arr[k]                count += 1                 # If 5 consecutive set bits                # are found insert a 0 bit                if (count == 5):                    j += 1                    brr[j] = 0                 i = k                k += 1         # Otherwise insert arr[i] into        # the array brr[]        else:            brr[j] = arr[i]         i += 1        j += 1     # Print Answer    for i in range(0, j):        print(brr[i], end = "") # Driver Codeif __name__ == "__main__":     N = 6    arr = [ 1, 1, 1, 1, 1, 1 ]     bitStuffing(N, arr) # This code is contributed by rakeshsahni
// C# program for the above approachusing System; class GFG{ // Function for bit stuffingstatic void bitStuffing(int N, int[] arr){         // Stores the stuffed array    int[] brr = new int[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            k = i + 1;            while (k < N && arr[k] == 1 && count < 5)            {                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;                k++;            }        }         // Otherwise insert arr[i] into        // the array brr[]        else        {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for(i = 0; i < j; i++)        Console.Write(brr[i]);} // Driver Codepublic static void Main(){    int N = 6;    int[] arr = { 1, 1, 1, 1, 1, 1 };     bitStuffing(N, arr);}} // This code is contributed by ukasp
<script>      // JavaScript Program to implement      // the above approach       // Function for bit stuffing      function bitStuffing(N, arr)      {                 // Stores the stuffed array          let brr = new Array(30);           // Variables to traverse arrays          let i, j, k;          i = 0;          j = 0;           // Stores the count of consecutive ones          let 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;                  }              }               // Otherwise insert arr[i] into              // the array brr[]              else {                  brr[j] = arr[i];              }              i++;              j++;          }           // Print Answer          for (i = 0; i < j; i++)              document.write(brr[i] + " ");      }       // Driver Code      let N = 6;      let arr = [1, 1, 1, 1, 1, 1];       bitStuffing(N, arr);   // This code is contributed by Potta Lokesh  </script>
1111101
Time Complexity: O(N)Auxiliary Space: O(N)
Bit Destuffing or Bit Unstuffing is a process of undoing the changes in the array made during the bit stuffing process i.e, removing the extra 0 bit after encountering 5 consecutive 1’s.
Examples: 
Input: N = 7, arr[] = {1, 1, 1, 1, 1, 0, 1}Output: 111111Explanation: During the traversal of the array, 5 consecutive 1’s are encountered after the 4th index of the given array. Hence, the next 0 bit must be removed to de-stuffed array. 
Input: N = 6, arr[] = {1, 0, 1, 0, 1, 0}Output: 101010
Approach: This problem can be solved similarly to the bit stuffing problem. The only required change in the above-discussed approach is whenever 5 consecutive 1’s are encountered, skip the next bit in the array arr[] in place of inserting a 0 bit in the array brr[]. 
Below is the implementation of the above approach: 
C
Java
Python3
C#
Javascript
// C program for the above approach#include <stdio.h>#include <string.h> // Function for bit de-stuffingvoid bitDestuffing(int N, int arr[]){    // 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 (arr[i] == 1) {             // Insert into array brr[]            brr[j] = arr[i];             // Loop to check for            // the 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 skip the                // next bit in arr[]                if (count == 5) {                    k++;                }                i = k;            }        }         // Otherwise insert arr[i] into        // the array brr        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        printf("%d", brr[i]);} // Driver Codeint main(){    int N = 7;    int arr[] = { 1, 1, 1, 1, 1, 0, 1 };     bitDestuffing(N, arr);     return 0;}
// Java program for the above approachclass GFG{ // Function for bit de-stuffingstatic void bitDestuffing(int N, int arr[]){       // Stores the de-stuffed array    int []brr = new int[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 (arr[i] == 1) {             // Insert into array brr[]            brr[j] = arr[i];             // Loop to check for            // the next 5 bits            for (k = i + 1; k<N &&                 arr[k] == 1                                   && count < 5;                 k++) {                j++;                brr[j] = arr[k];                count++;                 // If 5 consecutive set                // bits are found skip the                // next bit in arr[]                if (count == 5) {                    k++;                }                i = k;            }        }         // Otherwise insert arr[i] into        // the array brr        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        System.out.printf("%d", brr[i]);} // Driver Codepublic static void main(String[] args){    int N = 7;    int arr[] = { 1, 1, 1, 1, 1, 0, 1 };     bitDestuffing(N, arr);}} // This code is contributed by shikhasingrajput
# Python program for the above approach # Function for bit de-stuffingdef bitDestuffing(N, arr):       # Stores the de-stuffed array    brr = [0 for i in range(30)];     # Variables to traverse the arrays    k = 0;    i = 0;    j = 0;     # Stores the count of consecutive ones    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            # the next 5 bits            for k in range(i + 1, k < N and arr[k] == 1 and count < 5,1):                j += 1;                brr[j] = arr[k];                count += 1;                 # If 5 consecutive set                # bits are found skip the                # next bit in arr                if (count == 5):                    k += 1;                 i = k;           # Otherwise insert arr[i] into        # the array brr        else:            brr[j] = arr[i];         i += 1;        j += 1;     # PrAnswer    for i in range(0, j):        print(brr[i],end=""); # Driver Codeif __name__ == '__main__':    N = 7;    arr = [1, 1, 1, 1, 1, 0, 1];     bitDestuffing(N, arr); # This code contributed by shikhasingrajput
// C# program for the above approachusing System; class GFG{ // Function for bit de-stuffingstatic void bitDestuffing(int N, int[] arr){       // Stores the de-stuffed array    int []brr = new int[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 (arr[i] == 1) {             // Insert into array brr[]            brr[j] = arr[i];             // Loop to check for            // the next 5 bits            for (k = i + 1; k<N &&                 arr[k] == 1                                   && count < 5;                 k++) {                j++;                brr[j] = arr[k];                count++;                 // If 5 consecutive set                // bits are found skip the                // next bit in arr[]                if (count == 5) {                    k++;                }                i = k;            }        }         // Otherwise insert arr[i] into        // the array brr        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        Console.Write(brr[i]);} // Driver Codepublic static void Main(){    int N = 7;    int[] arr = { 1, 1, 1, 1, 1, 0, 1 };     bitDestuffing(N, arr);}} // This code is contributed by gfgking
<script>// javascript program for the above approach// Function for bit de-stuffingfunction bitDestuffing(N , arr){       // Stores the de-stuffed array    var brr = Array.from({length: 30}, (_, i) => 0);     // Variables to traverse the arrays    var i, j, k;    i = 0;    j = 0;     // Stores the count of consecutive ones    var 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            // the next 5 bits            for (k = i + 1; k<N &&                 arr[k] == 1                                   && count < 5;                 k++) {                j++;                brr[j] = arr[k];                count++;                 // If 5 consecutive set                // bits are found skip the                // next bit in arr                if (count == 5) {                    k++;                }                i = k;            }        }         // Otherwise insert arr[i] into        // the array brr        else {            brr[j] = arr[i];        }        i++;        j++;    }     // Print Answer    for (i = 0; i < j; i++)        document.write(brr[i]);} // Driver Codevar N = 7;var arr = [ 1, 1, 1, 1, 1, 0, 1 ]; bitDestuffing(N, arr); // This code is contributed by 29AjayKumar</script>
1111101
Time Complexity: O(N)Auxiliary Space: O(N)
 
lokeshpotta20
ukasp
rakeshsahni
shikhasingrajput
gfgking
29AjayKumar
surinderdawra388
target_2
Algorithms
Bit Magic
Computer Networks
Bit Magic
Algorithms
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?