51 lines
1.5 KiB
C
Executable file
51 lines
1.5 KiB
C
Executable file
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_utoa.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/10/22 17:36:09 by thrieg #+# #+# */
|
|
/* Updated: 2025/02/16 19:05:38 by thrieg ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
|
|
static size_t nb_digits(unsigned int n)
|
|
{
|
|
size_t i;
|
|
|
|
i = 0;
|
|
while (n > 0)
|
|
{
|
|
i++;
|
|
n /= 10;
|
|
}
|
|
return (i);
|
|
}
|
|
|
|
static void recursive_utoa(unsigned int n, char *ret, size_t *index)
|
|
{
|
|
if (n > 9)
|
|
recursive_utoa(n / 10, ret, index);
|
|
ret[(*index)++] = (n % 10) + '0';
|
|
}
|
|
|
|
//converts an unsigned int to a string, returns NULL if an allocation fails
|
|
//works for any size of unsigned int (future-proof)
|
|
char *ft_utoa(unsigned int n)
|
|
{
|
|
char *ret;
|
|
size_t index;
|
|
|
|
if (n == 0)
|
|
return (ft_strdup("0"));
|
|
ret = malloc(sizeof(char) * (nb_digits(n) + 1));
|
|
if (!ret)
|
|
return (NULL);
|
|
index = 0;
|
|
recursive_utoa(n, ret, &index);
|
|
ret[index] = '\0';
|
|
return (ret);
|
|
}
|