xref: /freebsd/contrib/ntp/libntp/hextoint.c (revision 86c9d9918f1db7cdd968b60f8902466887bcd9e9)
1 /*
2  * hextoint - convert an ascii string in hex to an unsigned
3  *	      long, with error checking
4  */
5 #include <config.h>
6 #include <ctype.h>
7 
8 #include "ntp_stdlib.h"
9 
10 int
11 hextoint(
12 	const char *str,
13 	u_long *pu
14 	)
15 {
16 	register u_long u;
17 	register const char *cp;
18 
19 	cp = str;
20 
21 	if (*cp == '\0')
22 		return 0;
23 
24 	u = 0;
25 	while (*cp != '\0') {
26 		if (!isxdigit((unsigned char)*cp))
27 			return 0;
28 		if (u & 0xF0000000)
29 			return 0;	/* overflow */
30 		u <<= 4;
31 		if ('0' <= *cp && *cp <= '9')
32 			u += *cp++ - '0';
33 		else if ('a' <= *cp && *cp <= 'f')
34 			u += *cp++ - 'a' + 10;
35 		else if ('A' <= *cp && *cp <= 'F')
36 			u += *cp++ - 'A' + 10;
37 		else
38 			return 0;
39 	}
40 	*pu = u;
41 	return 1;
42 }
43