I've just coded a hex to integer converter in C and want my code criticized. I did not cover switch statements so I know that can be improved. I am also planning to truncate "0x" in the beginning of the input if the user enters that.
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define MAXCHAR 100
int htoi(char hexArray[], int srraySize);
int main(void){
int userInput;
int i = 0;
char hexArray[MAXCHAR];
while((userInput = getchar()) != EOF){
if(userInput >= '0' && userInput <= '9'){
hexArray[i] = userInput;
++i;
}
if((userInput >= 'a' && userInput <= 'f') || (userInput >= 'A' && userInput <= 'F')){
hexArray[i] = userInput;
++i;
}
}
hexArray[++i] = '\0';
int ans = htoi(hexArray, i);
printf("%d\n", ans);
return 0;
}
int htoi(char hexArray[], int arraySize)
typedef enum{ a = 10,
b,
c,
d,
e,
f
} hexValues;
int intArray[MAXCHAR] = { 0 };
int i, j;
int finalAns = 0;
for(i = 0; i < arraySize; ++i){
if(hexArray[i] >= 'A' && hexArray[i] <= 'F'){
hexArray[i] = (char)tolower((int)hexArray[i]);
}
}
for(i = 0; i < arraySize; ++i){
if(hexArray[i] >= '0' && hexArray[i] <= '9'){
intArray[i] = hexArray[i];
} else if(hexArray[i] >= 'a' && hexArray[i] <= 'f'){
if(hexArray[i] == 'a'){
intArray[i] = a;
} else if(hexArray[i] == 'b'){
intArray[i] = b;
} else if(hexArray[i] == 'c'){
intArray[i] = c;
} else if(hexArray[i] == 'd'){
intArray[i] = d;
} else if(hexArray[i] == 'e'){
intArray[i] = e;
} else if(hexArray[i] == 'f'){
intArray[i] = f;
}
}
}
j = arraySize-2;
for(i = 0; i < arraySize-1; ++i){
printf("J = %d\n", j);
printf("Initial Value: %d\n", intArray[i]);
intArray[i] = (intArray[i] * (pow(16, j)));
printf("Processed Value: %d\n", intArray[i]);
finalAns = finalAns + intArray[i];
--j;
}
return finalAns;
}