libft/ft_itoa.c

44 lines
1.3 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tosuman <timo42@proton.me> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/03 11:32:41 by tosuman #+# #+# */
/* Updated: 2023/06/03 11:32:41 by tosuman ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
char *ft_itoa(int n)
{
char *str;
size_t n_len;
unsigned int n_cpy;
int is_neg;
is_neg = n < 0;
n_len = 0;
n_cpy = ft_abs(n) + !n;
while (n_cpy * ++n_len != 0)
n_cpy /= 10;
--n_len;
str = malloc(sizeof(*str) * (n_len + is_neg + 1));
if (!str)
return (0);
str += n_len + is_neg;
n_cpy = ft_abs(n);
*str-- = 0;
while (n_len--)
{
*str-- = n_cpy % 10 + '0';
n_cpy /= 10;
}
if (is_neg)
*str-- = '-';
return (++str);
}