-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
79 lines (72 loc) · 1.75 KB
/
ft_itoa.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
73
74
75
76
77
78
79
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mskeleto <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/12 17:58:55 by mskeleto #+# #+# */
/* Updated: 2020/11/23 20:30:32 by mskeleto ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count(int n)
{
int count;
count = 0;
if (n == 0)
return (1);
if (n < -2000000000)
return (10);
if (n < 0)
n *= -1;
while (n > 0)
{
n = n / 10;
count++;
}
return (count);
}
static void ft_convert_nbr(int n, int count, char *nbr)
{
int i;
int zero;
char d;
i = count;
zero = 1;
d = n % 10 + 48;
while (i-- > 1)
zero *= 10;
while (i++ <= count && (zero != 0))
{
d = n / zero + 48;
n %= zero;
zero /= 10;
*nbr = d;
nbr++;
}
*nbr = '\0';
}
char *ft_itoa(int n)
{
char *nbr;
int count;
int plus;
count = ft_count(n);
plus = (n < 0);
nbr = (char*)(malloc((count + 1 + plus) * (sizeof(char))));
if (nbr == NULL)
return (NULL);
if (n == -2147483648)
nbr = ft_memcpy(nbr, "-2147483648", 12);
else
{
if (n < 0)
{
*nbr = '-';
n *= -1;
}
ft_convert_nbr((n), count, (nbr + plus));
}
return (nbr);
}