L-23 MCS 260 Fri 12 Oct 2001
In this lecture we have seen one "big" application.
Because we focused in the lecture on the bits and pieces,
we did not really get to the whole program, see below :
/* L-23 MCS 260 Fri 12 Oct 2001 : distorting a sequence of characters
The program below simulates what happens if a sequence of
characters is passed through a noisy channel, when bits in
the ASCII code of the characters are distorted.
For every character, there is a 15% chance for 1 bit error
and an 5% chance for 2 bit error. So the character is transmitted
right in 85% of all cases.
If the distorted character is not printable or a control character,
then we discard the errors and print out the original character.
We add this restriction to keep the program user friendly.
As usual, the program runs via redirection, e.g.: a.out < distort.c
Following are prototypes of the functions we use : */
int distort ( int c );
/* returns c with probability 0.80,
c + one bit flipped with probability 0.10,
c + two bit flipped with probability 0.05. */
/* distort first determines the size of the error and, in case the
size of the error is larger than 0, flips bits : */
int size_error ( void );
/* returns 0 with probability 0.80,
1 with probability 0.10,
2 with probability 0.05 */
int flip_bit ( int c, int bitpos );
/* flips a bit (i.e.: 0 becomes 1 and 1 becomes 0) in the character c,
on the given position bitpos, where bitpos is between 0 and 3;
the distorted character is returned */
#include<stdio.>
#include<stdlib.h>
#include<time.h>
#include<ctype.h>
int main(void)
{
int c;
srand(time(NULL));
while ((c = getchar()) != EOF)
putchar(distort(c));
return 0;
}
int size_error ( void )
{
float r = (float) rand()/RAND_MAX;
if (r < 0.05)
return 2;
else if (r < 0.15)
return 1;
else
return 0;
}
int flip_bit ( int c, int bitpos )
{
int i,error = 1;
int wrk = c;
for (i = 0; i < bitpos; i++)
{
error *= 2;
wrk /= 2;
}
if (wrk % 2 == 0)
return (c + error);
else
return (c - error);
}
int distort ( int c )
{
int size = size_error();
int b1,b2,result = c;
if (size > 0)
{
b1 = rand() % 8;
result = flip_bit(c,b1);
if (size == 2)
{
b2 = b1;
while (b2 == b1) b2 = rand() % 8;
result = flip_bit(result,b2);
}
}
if (iscntrl(result) || (!isprint(result)))
return c;
else
return result;
}