atouint.c 903 Bytes
Newer Older
1
#include <config.h>
2 3 4 5 6 7
#include <sys/types.h>
#include <ctype.h>

#include "ntp_types.h"
#include "ntp_stdlib.h"

8 9
/*
 * atouint() - convert an ascii string representing a whole base 10
10 11
 *	       number to u_long *uval, returning true if successful.
 *	       Does not modify *uval and returns false if str is not
12 13
 *	       a positive base10 integer or is too large for a uint32_t.
 *	       this function uses u_long but should use uint32_t, and
14 15
 *	       probably be renamed.
 */
16
bool
17 18 19 20 21
atouint(
	const char *str,
	u_long *uval
	)
{
22 23
	u_long u;
	const char *cp;
24 25

	cp = str;
26
	if ('\0' == *cp)
27
		return false;
28 29

	u = 0;
30
	while ('\0' != *cp) {
31
		if (!isdigit((unsigned char)*cp))
32
			return false;
33
		if (u > 429496729 || (u == 429496729 && *cp >= '6'))
34
			return false;		/* overflow */
35
		/* hand-optimized u *= 10; */
36
		u = (u << 3) + (u << 1);
37
		u += *cp++ - '0';		/* not '\0' */
38 39 40
	}

	*uval = u;
41
	return true;
42
}