convertbase fonctionne bien

This commit is contained in:
Hugo LAMY
2020-02-20 19:04:48 +01:00
parent b17ba4308f
commit 87af05c0cc

View File

@@ -1,23 +1,38 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_convertbase.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/20 19:02:50 by hulamy #+# #+# */
/* Updated: 2020/02/20 19:03:51 by hulamy ### ########.fr */
/* */
/* ************************************************************************** */
/*
** take a string that is a number in a certain and convert it in another base
** return the new string
*/
#include <stdio.h> // for printf
#include <stdlib.h> // for atoi
char *ft_convertbase(char *nbr, char *base_from, char *base_to);
int main(int ac, char **av)
{
if (ac != 4)
printf("usage:\nchar *nbr, char *base_from, char *base_to\ntry the max long unsigned int : 9223372036854775807");
else
printf("[%s]\n",ft_convertbase(av[1], av[2], av[3]));
return (0);
}
/*
** #include <stdio.h> // for printf
** #include <stdlib.h> // for atoi
**
** char *ft_convertbase(char *nbr, char *base_from, char *base_to);
**
** int main(int ac, char **av)
** {
** if (ac != 4)
** {
** printf("usage:\nchar *nbr, char *base_from, char *base_to\n");
** printf("try the max long unsigned int : 18446744073709551615\n");
** }
** else
** printf("[%s]\n",ft_convertbase(av[1], av[2], av[3]));
** return (0);
** }
*/
#include "libft.h"
@@ -84,6 +99,8 @@ int
** -transform a nbr written as a string into a decimal nbr
** -it's an unsigned nbr because the negativity is managed elsewhere
** -if the number is bigger than the max unsigned long int it's false
** as it's impossible to verify if a number is bigger than the biggest
** unsigned, we verify the difference before the multiplication
*/
unsigned long int
@@ -104,7 +121,7 @@ unsigned long int
j = 0;
while (nbr[i] != base[j] && base[j])
j++;
if ((18446744073709551615U - j) / length > decimal)
if ((18446744073709551615U - j) / length < decimal)
return (0);
decimal = (decimal * length) + j;
i++;
@@ -112,13 +129,20 @@ unsigned long int
return (decimal);
}
/*
** -it counts the size needed to be allocated
** -if the given nbr was a negative one it add the place for the '-'
** -then convert the nbr from decimal base to destination base
** into the string allocated
*/
char
*decimal_to_base(unsigned long int decimal, char *base, int malloc_size)
{
int base_size;
int neg;
char *result;
unsigned long int nb;
int base_size;
int neg;
char *result;
unsigned long int nb;
neg = malloc_size;
base_size = 0;
@@ -139,6 +163,10 @@ char
return (result);
}
/*
** main function to convert from one base to another
*/
char
*ft_convertbase(char *nbr, char *base_from, char *base_to)
{