ft_itoa.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_itoa.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: mazimi <mazimi@student.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2014/12/09 14:15:57 by mazimi #+# #+# */
  9. /* Updated: 2016/09/26 14:18:43 by mazimi ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "../libft.h"
  13. static char *ft_turn(char *src, int lon)
  14. {
  15. char *dest;
  16. int i;
  17. int j;
  18. dest = ft_strnew(lon);
  19. j = lon;
  20. i = -1;
  21. while (++i < lon)
  22. dest[i] = src[--j];
  23. return (dest);
  24. }
  25. static int intlen(int c)
  26. {
  27. int i;
  28. int lon;
  29. i = 1;
  30. if (c < 0)
  31. i++;
  32. lon = c;
  33. while (lon >= 10 || lon <= -10)
  34. {
  35. lon = lon / 10;
  36. i++;
  37. }
  38. return (i);
  39. }
  40. char *ft_itoa(int c)
  41. {
  42. int lon;
  43. char *str;
  44. char *dst;
  45. int cc;
  46. int i;
  47. if (c == -2147483648)
  48. return (ft_strdup("-2147483648"));
  49. cc = c;
  50. lon = intlen(c);
  51. str = ft_strnew(lon);
  52. if (c < 0)
  53. c = -c;
  54. i = -1;
  55. while (++i < lon)
  56. {
  57. str[i] = (c % 10) + 48;
  58. c = c / 10;
  59. }
  60. if (cc < 0)
  61. str[i - 1] = '-';
  62. dst = ft_turn(str, lon);
  63. return (dst);
  64. }