csnotes/334/homework/1/bindec.c

65 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// max length input string
#define MAXSTR 25
// convert input binary string to a number
int bindec(char*, size_t);
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\n", MAXSTR);
exit(1);
}
for(size_t i = 0; i < n; i++) {
if(s[i] == '0' || s[i] == '1') {
continue;
}
else {
printf("input must contain only zeros and ones\n");
exit(1);
}
}
if(!n) {
printf("No input given only hit enter\n");
exit(1);
}
int output = bindec(s, MAXSTR);
printf("%d\n", output);
return 0;
}
int bindec(char* buf, size_t len) {
int ret = 0;
for(size_t i = 0; i < len; i++) {
if(buf[i] == '1') {
ret <<= 1;
ret++;
}
else {
ret <<= 0;
}
}
return ret;
}