42_solong/libftx/extra/ft_ultoa_base.c
Camille Chauvet 8b200fb8ba kekw
2023-01-19 13:41:58 +01:00

90 lines
1.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ultoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/29 13:49:45 by cchauvet #+# #+# */
/* Updated: 2023/01/19 13:01:09 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "extra.h"
static size_t ft_str_size(unsigned long long n, size_t base_size)
{
size_t size;
size = 1;
if (n == 0)
return (2);
while (n != 0)
{
n = n / base_size;
size++;
}
return (size);
}
static int ft_isdup(char *str)
{
char c;
size_t i;
while (*str != 0)
{
c = *str;
i = 1;
while (str[i] != 0)
{
if (str[i] == c)
return (1);
i++;
}
str++;
}
return (0);
}
static size_t ft_base_size(char *base)
{
size_t len;
if (ft_isdup(base))
return (0);
len = ft_strlen(base);
if (len < 2)
return (0);
return (len);
}
char *ft_ultoa_base(unsigned long long n, char *base)
{
size_t base_size;
int str_size;
char *out;
size_t i;
if (base == NULL)
return (NULL);
base_size = ft_base_size(base);
if (base_size == 0)
return (NULL);
str_size = ft_str_size(n, base_size);
out = ft_calloc(str_size + 1, sizeof(char));
if (out == NULL)
return (NULL);
i = 0;
if (n == 0)
out[0] = base[0];
while (n != 0)
{
out[str_size - 2 - i] = base[n % base_size];
n /= base_size;
i++;
}
out[str_size - 1] = '\0';
return (out);
}