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.
-
set v = 0
-
For each digit (from left to right)
-
v = v * base;
-
v = v + digit;
-
-
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:
-
offset = 0x30;
-
number = 0;
-
retval = read(0, &ascii_value, 1);
-
while (retval == 1)
-
digit = ascii_value - offset;
-
number = ( number << 1 ) + digit; // same thing as: number = number * 2 + digit;
-
retval = read(0, &ascii_value, 1);
-
-
printf("%u ", number); # the %u indicates that 'number' is an unsigned quanity
-
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started