-
Notifications
You must be signed in to change notification settings - Fork 3
/
ft_itoa_base.c
72 lines (66 loc) · 1.92 KB
/
ft_itoa_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
69
70
71
72
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lsauvage <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/29 15:33:51 by lsauvage #+# #+# */
/* Updated: 2018/03/29 16:52:44 by lsauvage ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
static size_t digit_count(long nb, int base)
{
size_t i;
i = 0;
while (nb)
{
nb /= base;
i++;
}
return (i);
}
char *ft_itoa_base(int value, int base)
{
char *ret;
char *tab_base;
int taille;
int i;
int sign;
if (base < 2 || base > 16)
return (0);
if (base == 10 && value == -2147483648)
return ("-2147483648");
sign = 0;
if (base == 10 && value < 0)
sign = 1;
if (value < 0)
value = -value;
if (value == 0)
return ("0");
tab_base = (char *)malloc(sizeof(char) * 17);
tab_base = "0123456789ABCDEF";
taille = digit_count(value, base);
taille += (sign ? 1 : 0);
ret = (char *)malloc(sizeof(char) * (taille + 1));
i = 1;
sign ? (ret[0] = '-') : 0;
while (value != 0)
{
ret[taille - i++] = tab_base[value % base];
value /= base;
}
ret[taille] = '\0';
return (ret);
}
int main(int ac, const char **av)
{
if (ac == 3)
{
printf("taille de value : %zu\n", digit_count(atoi(av[1]), atoi(av[2])));
printf("itoa : %s\n", ft_itoa_base(atoi(av[1]), atoi(av[2])));
}
return (0);
}