ft_nm/ft_printf/libft/ft_u_convert.c

114 lines
2.5 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_u_convert.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pbonilla <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/22 19:22:14 by pbonilla #+# #+# */
/* Updated: 2021/03/19 19:07:30 by pbonilla ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
int u_isinbase(char c, char *base)
{
int i;
i = 0;
while (base[i])
{
if (base[i] == c)
return (i);
++i;
}
return (-1);
}
long u_ft_atoi_base(char *str, char *base)
{
int len_base;
int i;
int signe;
unsigned long long nbr;
signe = 1;
i = 0;
nbr = 0;
len_base = ft_strlen(base);
while (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
signe *= -1;
i++;
}
while (u_isinbase(str[i], base) >= 0)
{
nbr = (len_base * nbr) + u_isinbase(str[i], base);
i++;
}
return (signe * nbr);
}
int u_get_size_in_char(unsigned long long nbr, int len_base)
{
int i;
i = 1;
while (nbr / len_base)
{
nbr = nbr / len_base;
++i;
}
return (i);
}
char *u_write_base(char *s, unsigned long long n,
char *b, int *i)
{
unsigned long long len_base;
unsigned long long nb;
len_base = ft_strlen(b);
nb = n;
if (nb >= len_base)
{
s[i[0]] = b[nb % len_base];
i[0] += 1;
u_write_base(s, nb / len_base, b, i);
}
else
{
s[i[0]] = b[nb];
if (i[1])
s[i[0] + 1] = '-';
s[i[0] + 1 + i[1]] = 0;
}
return (s);
}
char *ft_u_convert(char *nbr, char *b_f, char *b_t)
{
char *str;
int len_base;
int size_char;
unsigned long long number;
int i_sgn[2];
i_sgn[0] = 0;
i_sgn[1] = 0;
if (!nbr || !b_f || !b_t)
return (NULL);
number = u_ft_atoi_base(nbr, b_f);
len_base = ft_strlen(b_t);
size_char = u_get_size_in_char(number, len_base);
if (!(str = malloc(sizeof(char) * (size_char + 1))))
return (ft_strdup(""));
str = u_write_base(str, number, b_t, i_sgn);
str[size_char] = 0;
ft_rev_int_tab(str, size_char);
return (str);
}