1 /*        $NetBSD: atoint.c,v 1.8 2020/05/25 20:47:24 christos Exp $  */
2 
3 /*
4  * atoint - convert an ascii string to a signed long, with error checking
5  */
6 #include <config.h>
7 #include <sys/types.h>
8 #include <ctype.h>
9 
10 #include "ntp_types.h"
11 #include "ntp_stdlib.h"
12 
13 int
atoint(const char * str,long * ival)14 atoint(
15           const char *str,
16           long *ival
17           )
18 {
19           register long u;
20           register const char *cp;
21           register int isneg;
22           register int oflow_digit;
23 
24           cp = str;
25 
26           if (*cp == '-') {
27                     cp++;
28                     isneg = 1;
29                     oflow_digit = '8';
30           } else {
31                     isneg = 0;
32                     oflow_digit = '7';
33           }
34 
35           if (*cp == '\0')
36               return 0;
37 
38           u = 0;
39           while (*cp != '\0') {
40                     if (!isdigit((unsigned char)*cp))
41                         return 0;
42                     if (u > 214748364 || (u == 214748364 && *cp > oflow_digit))
43                         return 0;       /* overflow */
44                     u = (u << 3) + (u << 1);
45                     u += *cp++ - '0';   /* ascii dependent */
46           }
47 
48           if (isneg)
49               *ival = -u;
50           else
51               *ival = u;
52           return 1;
53 }
54