/* converts a string of hexadecimal digits (including an optional 0x * or 0X) into its equivalent integer value. The allowable digits are * 0 through 9, a through f, and A through F. */ #define MAXLEN 50 /* maximum allowable length of the number to be converted */ #include #include int main() { char c, count, arg[MAXLEN]; int result; count = 0; while ((c = getchar()) != EOF && c != '\t' && c != '\n' && c != ' ') { if (count < MAXLEN) arg[count++] = c; else break; } arg[count] = '\0'; result = htoi(arg); printf("Hex entered: %s\n", arg); printf("Integer equivalent: %d\n", result); return 0; } int htoi(char arg[]) { int i, result; i = result = 0; if (arg[i] == '0') { i++; if (arg[i] == 'x' || arg[i] == 'X') i++; } while (arg[i] != '\0') { if (arg[i] >= 'a' && arg[i] <= 'f') { result = result * 16 + arg[i] - 'a' + 10; i++; } else if (arg[i] >= 'A' && arg[i] <= 'F') { result = result * 16 + arg[i] - 'A' + 10; i++; } else if (arg[i] >= '0' && arg[i] <= '9') { result = result * 16 + arg[i] - '0'; i++; } else { printf("Invalid data, foo.\n"); exit(0); } } return result; } /* i'm a noob */