56 lines
1.5 KiB
C
56 lines
1.5 KiB
C
|
/* ************************************************************************** */
|
||
|
/* */
|
||
|
/* ::: :::::::: */
|
||
|
/* ft_itoabase.c :+: :+: :+: */
|
||
|
/* +:+ +:+ +:+ */
|
||
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
||
|
/* +#+#+#+#+#+ +#+ */
|
||
|
/* Created: 2022/09/29 13:49:45 by cchauvet #+# #+# */
|
||
|
/* Updated: 2022/10/06 18:22:32 by cchauvet ### ########.fr */
|
||
|
/* */
|
||
|
/* ************************************************************************** */
|
||
|
|
||
|
#include "libftprintf.h"
|
||
|
|
||
|
static size_t ft_nb_digit(int n, size_t base_size)
|
||
|
{
|
||
|
int out;
|
||
|
|
||
|
out = 0;
|
||
|
while (n)
|
||
|
{
|
||
|
n /= base_size;
|
||
|
out++;
|
||
|
}
|
||
|
return (out);
|
||
|
}
|
||
|
|
||
|
char *ft_itoabase(int n, char *base)
|
||
|
{
|
||
|
char *out;
|
||
|
unsigned int nb[2];
|
||
|
|
||
|
if (!n)
|
||
|
return (ft_ctoa(base[0]));
|
||
|
nb[0] = ft_nb_digit(n, ft_strlen(base));
|
||
|
if (n < 0)
|
||
|
{
|
||
|
nb[1] = -n;
|
||
|
nb[0]++;
|
||
|
}
|
||
|
else
|
||
|
nb[1] = n;
|
||
|
out = malloc(sizeof(char) * (nb[0] + 1));
|
||
|
if (out == NULL)
|
||
|
return (NULL);
|
||
|
out[nb[0]--] = 0;
|
||
|
if (n < 0)
|
||
|
out[0] = '-';
|
||
|
while (nb[1])
|
||
|
{
|
||
|
out[nb[0]--] = base[nb[1] % ft_strlen(base)];
|
||
|
nb[1] /= ft_strlen(base);
|
||
|
}
|
||
|
return (out);
|
||
|
}
|