Can someone help me with a c++ program that reads in a sequence of binary digits (values 0 and 1) and stores them into a STL container. The input should terminate on any input that is not a 0 or 1. After finishing the read-process, apply a "bit-stuffing" algorithm to the container. In this case the bit stuffing should occur after four consecutive bits of the same value.i,e. four 0's or four 1's..
Also write the de-stuffing code to process the stuffed data to recreate the original data and verify that the original data is recovered correctly.
@Bourgond Aries,
That's good. Thanks for bringing this up. I though about it first, but the problem is in this case any non-zero case is considered as true (i.e. 1, 2, 3, ... are true).
Is there a way to force the true case to be only 1??
Doesn't the while loop limit input data to 0 and 1? Also I don't think you need the extra parenthesis there.
To force the true case to only be 1? Perhaps the tenary operator can be of good use?
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
// read bits '0'/'1' into a string; terminate on any other char
std::string data_stream ;
char bit ;
while( std::cin >> bit && ( bit == '0' || bit == '1' ) ) data_stream += bit ;
// stuff a zero bit after four consecutive bits of the same value.
std::string stuffed_stream ;
int cnt = 0 ;
char bit_last_seen = 0 ;
int stuff_bits_added = 0 ;
for( bit<=data_stream); //for each bit in the data_stream
{
if( bit==bit_last_seen) //it is the same as the previous bit
cnt++;
else // it is a different bit
{
bit_last_seen := this bit ;
cnt := 1 ; // restart count at 1
}
stuffed_stream += bit ; // add the bit
if( cnt == 4 ) // there are four consecutive bits of the same value
{
stuffed_stream += '0' ; // stuff with a zero bit
cnt := 0 ; // and reset cnt to zero
++stuff_bits_added ; // increment the count of stuff bits added
}
}
std::string destuffed_stream ;
int cnt = 0 ;
char bit_last_seen = 0 ;
int stuff_bits_added = 0 ;
for( bit<=data_stream); //for each bit in the data_stream
{
if( bit==bit_last_seen) //it is the same as the previous bit
cnt--;
else // it is a different bit
{
bit_last_seen := this bit ;
cnt := 1 ; // restart count at 1
}
stuffed_stream -= bit ; // sub the bit
if( cnt == 4 ) // there are four consecutive bits of the same value
{
destuffed_stream += '0' ; // stuff with a zero bit
cnt := 4 ; // and reset cnt to 4
--stuff_bits_added ; // decrement the count of stuff bits added
}
}
// print out the results
std::cout << " data stream: " << data_stream << '\n'
std::cout << " stuffed stream: " << stuffed_stream << '\n'
std::cout << "stuff bits added: " << stuff_bits_added << '\n' ;
std::cout << "de-stuff bits added: " << destuffed_stream << '\n' ;
}