85 lines
1.9 KiB
C
85 lines
1.9 KiB
C
|
/* ************************************************************************** */
|
||
|
/* */
|
||
|
/* ::: :::::::: */
|
||
|
/* ft_ultoabase.c :+: :+: :+: */
|
||
|
/* +:+ +:+ +:+ */
|
||
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
||
|
/* +#+#+#+#+#+ +#+ */
|
||
|
/* Created: 2022/09/29 13:49:45 by cchauvet #+# #+# */
|
||
|
/* Updated: 2022/10/10 14:45:46 by cchauvet ### ########.fr */
|
||
|
/* */
|
||
|
/* ************************************************************************** */
|
||
|
|
||
|
#include "printf.h"
|
||
|
|
||
|
static size_t ft_str_size(unsigned 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_ultoabase(unsigned long n, char *base)
|
||
|
{
|
||
|
size_t base_size;
|
||
|
size_t str_size;
|
||
|
char *out;
|
||
|
|
||
|
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 = malloc(str_size * sizeof(char *));
|
||
|
if (out == NULL)
|
||
|
return (NULL);
|
||
|
out[--str_size] = 0;
|
||
|
while (0 < str_size)
|
||
|
{
|
||
|
out[--str_size] = base[n % base_size];
|
||
|
n = n / base_size;
|
||
|
}
|
||
|
return (out);
|
||
|
}
|