/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/20 15:50:47 by narnaud #+# #+# */ /* Updated: 2021/11/15 12:10:47 by narnaud ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static void ft_strrev(char **str, unsigned int neg) { char ch; size_t size; size_t i; size = ft_strlen(*str); if (neg) (*str)[size++] = '-'; i = 0; while (i < size / 2) { ch = (*str)[i]; (*str)[i] = (*str)[size - i - 1]; (*str)[size - i - 1] = ch; i++; } } static size_t get_nbrlength(int nbr) { size_t i; i = 0; if (nbr == 0) return (1); else if (nbr < 0) i++; while (nbr && ++i) nbr = nbr / 10; return (i); } char *ft_itoa(int n) { char *ret; unsigned int i; unsigned int neg; if (n == -2147483648) return (ft_strdup("-2147483648")); if (n == 0) return (ft_strdup("0")); i = 0; neg = 0; ret = ft_calloc(get_nbrlength(n) + 1, sizeof(char)); if (!ret) return (NULL); if (n < 0) { n = -n; neg = 1; } while (n) { ret[i++] = (n % 10) + '0'; n = n / 10; } ft_strrev(&ret, neg); return (ret); }