You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.6 KiB

#include <stdlib.h>
#include "convert_base.h"
long decode(char *nbr, char *base_from)
{
int i;
long result;
i = 0;
result = 0;
while (nbr[i] == 32 || (nbr[i] >= 9 && nbr[i] <= 13)
|| nbr[i] == 43 || nbr[i] == 45)
i++;
while (nbr[i] != '\0' && is_base(nbr[i], base_from))
{
result = (result * check(base_from)) + unchar(nbr[i], base_from);
i++;
}
if (nbr [i] != '\0' && !is_base(nbr[i], base_from))
abort();
return (result);
}
void convert(long medium, char *base_to,
char *unestring, int *p_i)
{
long l_base;
l_base = check(base_to);
if (medium >= 0 && medium < l_base)
{
unestring[*p_i] = base_to[medium];
*p_i = *p_i + 1;
}
if (medium >= l_base)
{
convert(medium / l_base, base_to, unestring, p_i);
convert(medium % l_base, base_to, unestring, p_i);
}
unestring[*p_i] = '\0';
}
char *jonemar(char *cepafini, char *celafin, int i)
{
int j;
j = 0;
while (cepafini[j])
{
celafin[i] = cepafini[j];
i++;
j++;
}
celafin[i] = '\0';
return (celafin);
}
char *recode(long medium, char *base_to, int posi)
{
int i;
char cepafini[50];
char *celafin;
i = 0;
convert(medium, base_to, cepafini, &i);
if (posi < 0)
celafin = (char *)malloc(sizeof(char) * (i + 2));
else
celafin = (char *)malloc(sizeof(char) * (i + 1));
if (!(celafin))
return (0);
if (posi < 0 && medium != 0)
{
i = 1;
celafin[0] = '-';
}
else
i = 0;
return (jonemar(cepafini, celafin, i));
}
char *convert_base(char *nbr, char *base_from, char *base_to)
{
if (!(check(base_from)) || !(check(base_to)))
return (NULL);
return (recode(decode(nbr, base_from), base_to, start(nbr)));
}