Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / external / bsd / ntp / dist / libntp / hextoint.c
blobaeb81e2b171e1737bb7df6afac015a632882a50e
1 /* $NetBSD$ */
3 /*
4 * hextoint - convert an ascii string in hex to an unsigned
5 * long, with error checking
6 */
7 #include <ctype.h>
9 #include "ntp_stdlib.h"
11 int
12 hextoint(
13 const char *str,
14 u_long *pu
17 register u_long u;
18 register const char *cp;
20 cp = str;
22 if (*cp == '\0')
23 return 0;
25 u = 0;
26 while (*cp != '\0') {
27 if (!isxdigit(*cp))
28 return 0;
29 if (u & 0xF0000000)
30 return 0; /* overflow */
31 u <<= 4;
32 if ('0' <= *cp && *cp <= '9')
33 u += *cp++ - '0';
34 else if ('a' <= *cp && *cp <= 'f')
35 u += *cp++ - 'a' + 10;
36 else if ('A' <= *cp && *cp <= 'F')
37 u += *cp++ - 'A' + 10;
38 else
39 return 0;
41 *pu = u;
42 return 1;