learningc/chapters/2/exercises/3.c

47 lines
924 B
C

#include <stdio.h>
#include <math.h>
#include "shared/functions.h"
#include "shared/functions/getlines.c"
#define MAXLINE 1024
int htoi(char s[], int l);
int main() {
char line[MAXLINE];
int out, len;
while ((len = getlines(line,MAXLINE)) != EOF) {
out = htoi(line,len);
}
printf("Result: %i\n", out);
return 0;
}
int htoi(char s[], int l) {
int num = 0, i, e;
for (i = l-1,e = 0; s[i] != 'x' && s[i] != 'X' && e <= 8; i--, e++) {
int c = 0;
switch (s[i]) {
case 'F': case 'f': c++;
case 'E': case 'e': c++;
case 'D': case 'd': c++;
case 'C': case 'c': c++;
case 'B': case 'b': c++;
case 'A': case 'a': c++;
case '9': c++;
case '8': c++;
case '7': c++;
case '6': c++;
case '5': c++;
case '4': c++;
case '3': c++;
case '2': c++;
case '1': c++;
default: break;
}
int mul = 1;
if (e != 0) {
mul = pow(16,e);
}
num = num + (mul * c);
}
return num;
}