1 /*
2  * Copyright (C) 1998,1999 Uwe Ohse
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *
18  * As a special exception this source may be used as part of the
19  * SRS project by CORE/Computer Service Langenbach
20  * regardless of the copyright they choose.
21  *
22  * Contact: uwe@ohse.de
23  */
24 /* written mainly to get around the need to include a strtoul.c in the distributions */
25 #include "config.h"
26 #include "str2num.h"
27 
28 int
str2ulong(const char * s,unsigned long * ul,int base)29 str2ulong (const char *s, unsigned long *ul, int base)
30 {
31 	unsigned long x = 0;
32 	const char *t = s;
33 	if (base == 0 && *s == '0') {
34 		if (s[1] == 'x' || s[1] == 'X') {
35 			base = 16;
36 			s += 2;
37 		} else {
38 			base = 8;
39 			s++;
40 			if (!*s) {
41 				*ul = 0;
42 				return 1;
43 			}
44 		}
45 	} else if (base == 0)
46 		base = 10;
47 	else if (base == 16 && *s == '0') {		/* as strtoul compatible as possible */
48 		if ((s[1] == 'x' || s[1] == 'X') && s[2])
49 			s += 2;
50 	}
51 	/* i assume something about processor behaviour in case of overflow ... */
52 	/* and, of course, about the character set */
53 	while (*s) {
54 		unsigned int c = (unsigned char) *s;
55 		int v;
56 		unsigned long old;
57 		if (c < '0' || c > '9') {
58 			if (c >= 'a' && c <= 'z')
59 				v = (c - 'a');
60 			else if (c >= 'A' && c <= 'Z')
61 				v = (c - 'A');
62 			else
63 				goto out;
64 			v += 10;
65 		} else
66 			v = c - '0';
67 		if (v >= base)
68 			goto out;
69 		old = x;
70 		x *= (unsigned long) base;
71 		x += (unsigned long) v;
72 		if (x < old)
73 			return -1;
74 		s++;
75 	}
76   out:
77 	*ul = x;
78 	return s - t;
79 }
80