Move files out of root into core, dos, and utils
[profile/ivi/syslinux.git] / memdump / strtoul.c
1 /*
2  * strtoul.c
3  *
4  */
5
6 #include "mystuff.h"
7
8 static inline int isspace(int c)
9 {
10         return (c <= ' ');      /* Close enough */
11 }
12
13 static inline int digitval(int ch)
14 {
15         if (ch >= '0' && ch <= '9') {
16                 return ch - '0';
17         } else if (ch >= 'A' && ch <= 'Z') {
18                 return ch - 'A' + 10;
19         } else if (ch >= 'a' && ch <= 'z') {
20                 return ch - 'a' + 10;
21         } else {
22                 return -1;
23         }
24 }
25
26 unsigned long strtoul(const char *nptr, char **endptr, int base)
27 {
28         int minus = 0;
29         unsigned long v = 0;
30         int d;
31
32         while (isspace((unsigned char)*nptr)) {
33                 nptr++;
34         }
35
36         /* Single optional + or - */
37         {
38                 char c = *nptr;
39                 if (c == '-' || c == '+') {
40                         minus = (c == '-');
41                         nptr++;
42                 }
43         }
44
45         if (base == 0) {
46                 if (nptr[0] == '0' &&
47                     (nptr[1] == 'x' || nptr[1] == 'X')) {
48                         nptr += 2;
49                         base = 16;
50                 } else if (nptr[0] == '0') {
51                         nptr++;
52                         base = 8;
53                 } else {
54                         base = 10;
55                 }
56         } else if (base == 16) {
57                 if (nptr[0] == '0' &&
58                     (nptr[1] == 'x' || nptr[1] == 'X')) {
59                         nptr += 2;
60                 }
61         }
62
63         while ((d = digitval(*nptr)) >= 0 && d < base) {
64                 v = v * base + d;
65                 nptr++;
66         }
67
68         if (endptr)
69                 *endptr = (char *)nptr;
70
71         return minus ? -v : v;
72 }