/****************************************************************************** * Base to Decimal (hex to int) * * Solution to K&$ 2-3 (supposed to be called htoi.c for hex to int) * But this version is generalized through #defines to sort of work * with any base (11 and up), so I left out the leading 0x--actually * I forgot about it. * At first I was annoyed by how hard this seemed, coming so early * in the book. But after I worked it out it made sense. * * program: base_to_dec * by.....: yetimach * date...: 25 October 2024 * *****************************************************************************/ #include #include #include #define MAX 7 #define BASE 16 #define BASE_NAME "hex" #define END_LETTER 'f' void read_line(char string[], int max){ int c, i = 0; while (i < max && (c = getchar()) != '\n' && c != EOF){ string[i] = c; ++i; } } int power(int base, int pow){ int result = 1; if (pow == 0) return result; while (pow-- > 0) result *= base; return result; } int base_to_dec(char string[]){ int i = 0, result = 0, single_value; int degree = 0; while (string[i] != '\0') ++i; --i; while (i >= 0){ single_value = tolower(string[i]); if (string[i] >= '0' && string[i] <= '9'){ result += ((power(BASE, degree)) * (string[i] - '0')); }else if (single_value >= 'a' && single_value <= END_LETTER){ result += ((power(BASE, degree) * (single_value - 'a' + 10))); }else{ printf("\nInvalid %s value entered.\n", BASE_NAME); return -1; } ++degree; --i; } return result; } int main(void) { char string[MAX+1]; printf("\nEnter a %s value:", BASE_NAME); read_line(string, MAX); int result = base_to_dec(string); if (result != -1) printf("\nThat is %d in decimal.\n", result); return 0; }