/contrib/ntp/libntp/atoint.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 50 lines · 40 code · 7 blank · 3 comment · 14 complexity · b1c311470cb2499f9b47d124b6953989 MD5 · raw file

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