atoi.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Copyright (C) 1991, 1997 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, write to the Free
  13. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  14. 02111-1307 USA. */
  15. #include "api.h"
  16. long strtol(const char *s, char **endptr, int base)
  17. {
  18. int neg = 0;
  19. long val = 0;
  20. // gobble initial whitespace
  21. while (*s == ' ' || *s == '\t')
  22. s++;
  23. // plus/minus sign
  24. if (*s == '+')
  25. s++;
  26. else if (*s == '-')
  27. s++, neg = 1;
  28. // hex or octal base prefix
  29. if ((base == 0 || base == 16) && (s[0] == '0' && s[1] == 'x'))
  30. s += 2, base = 16;
  31. else if (base == 0 && s[0] == '0')
  32. s++, base = 8;
  33. else if (base == 0)
  34. base = 10;
  35. // digits
  36. while (1) {
  37. int dig;
  38. if (*s >= '0' && *s <= '9')
  39. dig = *s - '0';
  40. else if (*s >= 'a' && *s <= 'z')
  41. dig = *s - 'a' + 10;
  42. else if (*s >= 'A' && *s <= 'Z')
  43. dig = *s - 'A' + 10;
  44. else
  45. break;
  46. if (dig >= base)
  47. break;
  48. s++, val = (val * base) + dig;
  49. // we don't properly detect overflow!
  50. }
  51. if (endptr)
  52. *endptr = (char *) s;
  53. return (neg ? -val : val);
  54. }
  55. /* Convert a string to an int. */
  56. int atoi (const char *nptr)
  57. {
  58. return (int) strtol (nptr, (char **) NULL, 10);
  59. }
  60. /* Convert a string to an long int. */
  61. long int atol (const char *nptr)
  62. {
  63. return strtol (nptr, (char **) NULL, 10);
  64. }