Question: ASCII-2-Binary Algorithm Recall from class, the following algorithm was provided to convert a string of binary digits into a decimal number. set v = 0

ASCII-2-Binary Algorithm

Recall from class, the following algorithm was provided to convert a string of binary digits into a decimal number.

  1. set v = 0

  2. For each digit (from left to right)

    1. v = v * base;

    2. v = v + digit;

  3. print v

Let's create a new algorithm in which

  • the string of digits are not numbers but ASCII characters,

  • the read system call is used to perform the input operation, and

  • java-like syntax is use

The revised algorthm is as follows:

  1. offset = 0x30;

  2. number = 0;

  3. retval = read(0, &ascii_value, 1);

  4. while (retval == 1)

    1. digit = ascii_value - offset;

    2. number = ( number << 1 ) + digit; // same thing as: number = number * 2 + digit;

    3. retval = read(0, &ascii_value, 1);

  5. printf("%u ", number); # the %u indicates that 'number' is an unsigned quanity

  6. return 0;

Your task is to write a C program that

  • reads a string of ASCII values from stdin (notice on line 3 of the algorithm provided, you are reading these values one character at a time.)

  • converts the ASCII values into a unsigned decimal number

  • prints the final decimal number to stdout

You need to augment the algorthm in the following ways.

  • allow the string to be terminated by either

    • the end of file, or

    • the newline (nl) character: as depicted as LF and ' '

  • validate that each ASCII value is within the range: 48-49

  • an error in input should result in the program returning the value of 1

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!