Question
INSTRUCTIONS : Programming in C, Modify the code below so that it converts the input string into a number, and prints the number. Write the
INSTRUCTIONS: Programming in C,
Modify the code below so that it converts the input string into a number, and prints the number. Write the code to convert from binary to decimal yourself (dont use a library call). The code should respond to empty input with value 0, and should respond to invalid input with message input must contain only zeros and ones, and exit with value 1, indicating an error. Your code should be able to handle inputs of at least 20 binary digits.
****************************************************************************************************************************************************************
Some examples of how your program should work:
$ ./bindec
> 1001
9
$ ./bindec
> 11111111
255
$ ./bindec
> hello
input must contain only zeros and ones
$ ./bindec
> (no input given, just hit enter)
0
****************************************************************************************************************************************************************
#include
// max length input string #define MAXSTR 25
// convert input binary string to a number
int main() {
// user input string char s[MAXSTR+3];
// prompt for input printf("> ");
// read input string; at most MAXSTR+1 chars accepted // Note: this is tricky. If we accept only MAXSTR chars, // we can't see if user entered more chars and they are // being dropped by fgets. fgets(s, MAXSTR+3, stdin);
// check input length; n does not include final carriage return int n = strlen(s)-1; if (n > MAXSTR) { printf("input cannot be more than %d characters ", MAXSTR); exit(1); }
// convert s from a string in binary, to an int, and output
// YOUR CODE HERE
}
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