libft/ft_itoa.c
Etienne Rey-bethbeder b891447a0d 3.0
2022-10-14 22:43:08 +02:00

54 lines
1.4 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/04 17:12:52 by erey-bet #+# #+# */
/* Updated: 2022/10/10 22:15:30 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_itoa_bis(char *str, int len, int i, long nl)
{
while (len > 1)
{
len--;
str[i] = (nl / ft_power(10, len) % 10) + 48;
i++;
}
str[i] = nl % 10 + 48;
i++;
str[i] = '\0';
}
char *ft_itoa(int n)
{
char *str;
int len;
int i;
long nl;
nl = n;
nl *= (n > 0) - (n < 0);
len = ft_get_size(nl);
i = 0;
if (n < 0)
{
str = malloc(len + 2);
if (str == NULL)
return (NULL);
str[i] = '-';
i++;
}
else
str = malloc(len + 1);
if (str == NULL)
return (NULL);
ft_itoa_bis(str, len, i, nl);
return (str);
}