convertbase renvoyait null en cas de conversion de 0

This commit is contained in:
Hugo LAMY
2020-02-26 20:20:54 +01:00
parent a140f4640f
commit 0f11860c37

View File

@@ -5,13 +5,15 @@
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */ /* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/20 19:02:50 by hulamy #+# #+# */ /* Created: 2020/02/26 20:19:54 by hulamy #+# #+# */
/* Updated: 2020/02/20 19:03:51 by hulamy ### ########.fr */ /* Updated: 2020/02/26 20:20:14 by hulamy ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
/* /*
** take a string that is a number in a certain and convert it in another base ** take a string that is a number in a certain base
** and convert it in another base
** it works with unsigned long int
** return the new string ** return the new string
*/ */
@@ -104,7 +106,7 @@ int
*/ */
unsigned long int unsigned long int
base_to_decimal(char *nbr, char *base) base_to_decimal(char *nbr, char *base, int *error)
{ {
unsigned long int decimal; unsigned long int decimal;
int i; int i;
@@ -122,7 +124,7 @@ unsigned long int
while (nbr[i] != base[j] && base[j]) while (nbr[i] != base[j] && base[j])
j++; j++;
if ((18446744073709551615U - j) / length < decimal) if ((18446744073709551615U - j) / length < decimal)
return (0); return (*error = 1);
decimal = (decimal * length) + j; decimal = (decimal * length) + j;
i++; i++;
} }
@@ -164,7 +166,11 @@ char
} }
/* /*
** main function to convert from one base to another ** -main function to convert from one base to another
** -function base_to_decimal has an awfull int *error because it cannot
** return -1 in case of error, since it's an unsigned, and it cannot
** return 0 to check the error since it would be confusing with an actual
** return of 0 if the number to convert is 0
*/ */
char char
@@ -172,7 +178,9 @@ char
{ {
int length; int length;
unsigned long int decimal; unsigned long int decimal;
int error;
error = 0;
length = 0; length = 0;
if (nbr[0] == '-') if (nbr[0] == '-')
{ {
@@ -181,7 +189,8 @@ char
} }
if (!is_valid_nbr(nbr, base_from) || !is_valid_base(base_to)) if (!is_valid_nbr(nbr, base_from) || !is_valid_base(base_to))
return (NULL); return (NULL);
if ((decimal = base_to_decimal(nbr, base_from)) == 0) decimal = base_to_decimal(nbr, base_from, &error);
if (error == 1)
return (NULL); return (NULL);
return (decimal_to_base(decimal, base_to, length)); return (decimal_to_base(decimal, base_to, length));
} }