From a5a9014fd8e7fe96a12b9414d89e4c5e95c8f353 Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Sun, 28 Nov 2021 18:11:57 +0800 Subject: 2.3 --- 2/3.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 2/3.c diff --git a/2/3.c b/2/3.c new file mode 100644 index 0000000..d9e62e9 --- /dev/null +++ b/2/3.c @@ -0,0 +1,46 @@ +#include + +#define MAXLEN 1000 + +int htoi(char s[]); + +/* converts positive hex string to decimal */ +int main(int argc, char *argv[]) { + int i, c, d; + char s[MAXLEN]; + + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != EOF && c != '\n'; i++) { + s[i] = c; + } + s[i] = 0; + + d = htoi(s); + if (d < 0) + printf("invalid input: %s\n", s); + else + printf("decimal value: %d\n", d); + + return 0; +} + +int htoi(char s[]) { + int i, n; + char c; + + n = 0; + + for (i = 0; (c = s[i]) != 0; i++) { + if ((i == 0 && c == '0') || (i == 1 && (c == 'x' || c == 'X'))) + continue; + else if (c >= '0' && c <= '9') + n = 16 * n + (c - '0'); + else if (c >= 'A' && c <= 'F') + n = 16 * n + (c - 'A' + 10); + else if (c >= 'a' && c <= 'f') + n = 16 * n + (c - 'a' + 10); + else + return -1; + } + + return n; +} \ No newline at end of file -- cgit v1.2.3