atoi.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. int neg = 0;
  18. long val = 0;
  19. // gobble initial whitespace
  20. while (*s == ' ' || *s == '\t') {
  21. s++;
  22. }
  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. return (int)strtol(nptr, (char**)NULL, 10);
  58. }
  59. /* Convert a string to an long int. */
  60. long int atol(const char* nptr) {
  61. return strtol(nptr, (char**)NULL, 10);
  62. }