-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_convert_base.c
68 lines (62 loc) · 1.76 KB
/
ft_convert_base.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_convert_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edelangh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/07/12 21:21:31 by edelangh #+# #+# */
/* Updated: 2015/01/30 14:09:58 by edelangh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static size_t ft_power_s(size_t nb, int power)
{
if (power == 0)
return (1);
if (power < 0)
return (0);
return (nb * ft_power_s(nb, power - 1));
}
static size_t ft_getval(char *nbr, char *base_from)
{
size_t val;
int i;
int j;
size_t len;
len = ft_strlen(nbr);
val = 0;
i = -1;
while (nbr[++i])
{
j = -1;
while (nbr[i] != base_from[++j])
;
val += j * (len - i ? ft_power_s(10, len - i - 1) : 1);
}
return (val);
}
char *ft_convert_base(char *nbr, char *base_from, char *base_to)
{
char *res;
size_t val;
size_t len_base;
int i;
val = ft_getval(nbr, base_from);
len_base = ft_strlen(base_to);
res = (char*)malloc(sizeof(char) * (32));
i = 0;
if (val)
while (val > 0)
{
res[i] = base_to[val % len_base];
val /= len_base;
++i;
}
else
res[i++] = base_to[0];
res[i] = '\0';
res = ft_strrev(res);
return (res);
}