1 /* +-------------------------------------------------------------------+ */
2 /* | Copyright 1988,1991, David Koblas. | */
3 /* | Permission to use, copy, modify, and distribute this software | */
4 /* | and its documentation for any purpose and without fee is hereby | */
5 /* | granted, provided that the above copyright notice appear in all | */
6 /* | copies and that both that copyright notice and this permission | */
7 /* | notice appear in supporting documentation. This software is | */
8 /* | provided "as is" without express or implied warranty. | */
9 /* +-------------------------------------------------------------------+ */
10
11 #include <string.h>
12 #include <ctype.h>
13
14 #ifdef TEST
15 int
main(argc,argv)16 main(argc, argv)
17 int argc;
18 char **argv;
19 {
20 int i;
21 for (i = 1; i < argc; i++)
22 printf("%10s == %d\n", argv[i], atov(argv[i], 0));
23 }
24 #endif
25
26 int
atov(char * str,int type)27 atov(char *str, int type)
28 {
29 int sign = 1;
30 int i;
31 char c;
32 int val = 0, n;
33
34 i = 0;
35 while ((str[i] == ' ') || (str[i] == '\t'))
36 i++;
37 if (str[i] == '-') {
38 sign = -1;
39 i++;
40 } else if (str[i] == '+') {
41 sign = 1;
42 i++;
43 }
44 if (type == 0) {
45 if (str[i] == '0') {
46 i++;
47 if (str[i] == '%') {
48 i++;
49 type = 2;
50 } else if (str[i] == 'x') {
51 i++;
52 type = 16;
53 } else {
54 type = 8;
55 }
56 } else {
57 type = 10;
58 }
59 }
60 // Flawfinder: ignore (strlen)
61 for (; i < strlen(str); i++) {
62 c = str[i];
63 if (isdigit(c)) {
64 n = c - '0';
65 } else if (isupper(c)) {
66 n = c - 'A' + 10;
67 } else if (islower(c)) {
68 n = c - 'a' + 10;
69 } else {
70 goto out;
71 }
72 if (n >= type)
73 goto out;
74 val = (val * type) + n;
75 }
76 out:
77 return (val * sign);
78 }
79