Rev 8793 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
8687 | turbocat | 1 | #include |
2 | #include |
||
3 | #include |
||
4 | |||
5 | int getdigit(char ch, int base) |
||
6 | { |
||
7 | if (isdigit(ch)) ch-= '0'; |
||
8 | else |
||
9 | if (isalpha(ch) && ch <= 'Z') ch = 10 + ch - 'A'; |
||
10 | else |
||
11 | if (isalpha(ch)) ch = 10 + ch - 'a'; |
||
12 | else |
||
13 | return -1; |
||
14 | |||
15 | if (ch / base != 0) return -1; |
||
16 | |||
17 | return ch; |
||
18 | } |
||
19 | |||
20 | |||
21 | long int strtol (const char* str, char** endptr, int base) |
||
22 | { |
||
23 | long int res = 0; |
||
24 | int sign = 1; |
||
25 | |||
26 | if (base > 36) |
||
27 | { |
||
28 | errno = EINVAL; |
||
29 | goto bye; |
||
30 | } |
||
31 | |||
32 | while (isspace(*str)) str++; |
||
33 | |||
34 | if (*str == '-') { sign = -1; str++; } |
||
35 | else |
||
36 | if (*str == '+') str++; |
||
37 | |||
38 | if (base == 0 || base == 16) |
||
39 | { |
||
40 | if (*str == '0' && (str[1] == 'x' || str[1] == 'X')) |
||
41 | { |
||
42 | base = 16; |
||
43 | str += 2; |
||
44 | } |
||
45 | } |
||
46 | |||
47 | if (base == 0 && *str == '0') base = 8; |
||
48 | |||
49 | if (base == 0) base = 10; |
||
50 | |||
51 | |||
52 | int digit; |
||
53 | while ((digit = getdigit(*str, base)) >= 0) |
||
54 | { |
||
55 | res = base * res + digit; |
||
56 | str++; |
||
57 | if (res < 0) |
||
58 | { |
||
59 | errno = ERANGE; |
||
60 | if (sign > 0) |
||
61 | res = LONG_MAX; |
||
62 | else |
||
63 | res = LONG_MIN; |
||
64 | } |
||
65 | } |
||
66 | |||
67 | bye: |
||
68 | if (endptr) |
||
69 | *endptr = (char*)str; |
||
70 | |||
71 | return res * sign; |
||
72 | }>=> |
||
73 |