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