1 /*---------------------------------------------------------------------
2 strtoul() - convert a string to a unsigned long int and return it
4 Copyright (C) 2018-2023, Philipp Klaus Krause . krauseph@informatik.uni-freiburg.de
6 This library is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this library; see the file COPYING. If not, write to the
18 Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
21 As a special exception, if you link this library with other files,
22 some of which are compiled with SDCC, to produce an executable,
23 this library does not by itself cause the resulting executable to
24 be covered by the GNU General Public License. This exception does
25 not however invalidate any other reasons why the executable file
26 might be covered by the GNU General Public License.
27 -------------------------------------------------------------------------*/
34 #if !defined(__SDCC_pic14) && !defined(__SDCC_pic16)
35 #include <stdckdint.h>
40 static signed char _isdigit(const char c
, unsigned char base
)
44 if (c
>= '0' && c
<= '9')
46 else if (c
>= 'a' && c
<='z')
48 else if (c
>= 'A' && c
<='Z')
59 // NOTE for maintenance: strtoull, wcstoul and wcstoull have been derived from strtoul
61 unsigned long int strtoul(const char *nptr
, char **endptr
, int base
)
63 const char *ptr
= nptr
;
64 unsigned long int ret
;
65 bool range_error
= false;
67 unsigned char b
= base
;
69 while (isblank (*ptr
))
81 // base not specified.
84 if (!strncmp (ptr
, "0x", 2) || !strncmp (ptr
, "0X", 2))
89 else if (!strncmp (ptr
, "0b", 2) || !strncmp (ptr
, "0B", 2))
102 // Handle optional hex prefix.
103 else if (b
== 16 && (!strncmp (ptr
, "0x", 2) || !strncmp (ptr
, "0X", 2)))
105 else if (b
== 2 && (!strncmp (ptr
, "0b", 2) || !strncmp (ptr
, "0B", 2)))
108 // Empty sequence conversion error
109 if (_isdigit (*ptr
, b
) < 0)
112 *endptr
= (char*)nptr
;
116 for (ret
= 0;; ptr
++)
118 signed char digit
= _isdigit (*ptr
, b
);
123 #if !defined(__SDCC_pic14) && !defined(__SDCC_pic16)
124 range_error
|= ckd_mul (&ret
, ret
, b
);
125 range_error
|= ckd_add (&ret
, ret
, digit
);
127 unsigned long int oldret
= ret
;
131 ret
+= (unsigned char)digit
;
132 #warning INEXACT RANGE ERROR CHECK WILL NOT REPORT ALL OVERFLOWS (fix by implementing ckd_mul and ckd_add)
137 *endptr
= (char*)ptr
;
145 return (neg
? -ret
: ret
);