ft_malloc/libft/ft_utoa_base.c
2025-11-28 19:50:58 +01:00

93 lines
2.5 KiB
C
Executable file

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/23 13:59:32 by thrieg #+# #+# */
/* Updated: 2025/02/16 19:05:36 by thrieg ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "ft_vector.h"
static int ft_is_sign(char c)
{
if (c == '-' || c == '+')
return (1);
else
return (0);
}
//converts nbr into a known to be valid base, then append it to vec
//returns 0 if the concatenation fails, or 1 if everything goes well
static int ft_put_ok_base(
unsigned int nbr,
char *base,
size_t base_lenght,
t_vector *vec)
{
char buffer[32];
int i;
i = 31;
if (nbr == 0)
if (!ft_vector_pushback(vec, base[0]))
return (0);
while (nbr > 0)
{
buffer[i] = base[nbr % base_lenght];
nbr /= base_lenght;
i--;
}
if (!ft_vector_concat(vec, (buffer + i + 1), (31 - i)))
return (0);
return (1);
}
//returns 1 if the base is valid, and 0 if it's not
static int ft_is_ok_base(char *base)
{
char used_characters[128];
size_t i;
i = 0;
ft_bzero(used_characters, 128);
while (base[i] != '\0')
{
if (used_characters[(int) base[i]] == 0)
used_characters[(int) base[i]]++;
else
return (0);
if (ft_is_sign(base[i]))
return (0);
i++;
}
if (i < 2)
return (0);
return (1);
}
//returns a standard C string of nbr converted in the "base" base
//base have to only cointain ascii characters
//returns NULL if the base is invalid or if an allocation failed
char *ft_utoa_base(unsigned int unsigned_nbr, char *base)
{
t_vector *ret;
char *ret_str;
ret = ft_create_vector(2);
if (!ret)
return (NULL);
if (!ft_is_ok_base(base))
return (ft_free_vector(&ret), NULL);
if (!ft_put_ok_base(unsigned_nbr, base, ft_strlen(base), ret))
return (ft_free_vector(&ret), NULL);
ret_str = ft_vtoc(ret);
ft_free_vector(&ret);
if (!ret_str)
return (NULL);
return (ret_str);
}