stdlib.c 633 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <libc/unistd.h>
  2. #include <libc/stdlib.h>
  3. #include <libc/ctype.h>
  4. int abs(int i)
  5. {
  6. return i < 0 ? -i : i;
  7. }
  8. long labs(long i)
  9. {
  10. return i < 0 ? -i : i;
  11. }
  12. long long llabs(long long i)
  13. {
  14. return i < 0 ? -i : i;
  15. }
  16. int atoi(const char *str)
  17. {
  18. int n = 0, neg = 0;
  19. while (isspace(*str))
  20. {
  21. str++;
  22. }
  23. switch (*str)
  24. {
  25. case '-':
  26. neg = 1;
  27. break;
  28. case '+':
  29. str++;
  30. break;
  31. }
  32. /* Compute n as a negative number to avoid overflow on INT_MIN */
  33. while (isdigit(*str))
  34. {
  35. n = 10 * n - (*str++ - '0');
  36. }
  37. return neg ? n : -n;
  38. }