-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
87 lines (78 loc) · 1.78 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
80
81
82
83
84
85
86
87
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cbernot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/09 22:11:25 by cbernot #+# #+# */
/* Updated: 2022/11/13 18:45:14 by cbernot ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_nbrlen(int n)
{
int len;
len = 0;
if (n == 0)
len = 1;
if (n < 0)
{
len++;
n *= -1;
}
while (n > 0)
{
n = n / 10;
len++;
}
return (len);
}
static char *ft_minint_case(void)
{
char *res;
res = malloc(sizeof(char) * (12));
if (!res)
return (0);
ft_strlcpy(res, "-2147483648", 12);
return (res);
}
static char *ft_itoa2(int n, int len, char *res)
{
int i;
int offset;
offset = 0;
i = 0;
if (n == 0)
{
ft_strlcpy(res, "0", 2);
return (res);
}
if (n < 0)
{
res[0] = '-';
offset = 1;
n *= -1;
}
while (n > 0)
{
res[len - 1 - i] = (n % 10) + '0';
n = n / 10;
i++;
}
res[i + offset] = '\0';
return (res);
}
char *ft_itoa(int n)
{
int len;
char *res;
len = ft_nbrlen(n);
if (n == -2147483648)
return (ft_minint_case());
res = malloc(sizeof(char) * (len + 1));
if (!res)
return (0);
res = ft_itoa2(n, len, res);
return (res);
}