-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
91 lines (81 loc) · 1.92 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
88
89
90
91
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: joleksia <joleksia@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/07 15:16:39 by joleksia #+# #+# */
/* Updated: 2024/12/17 08:05:01 by joleksia ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int fts_numlen(int n);
static char *fts_strproc(char *s, int n);
static char *fts_strrev(char *s, size_t len);
char *ft_itoa(int n)
{
char *result;
result = (char *) ft_calloc(fts_numlen(n) + 1, sizeof(char));
if (!result)
return (NULL);
result = fts_strproc(result, n);
return (result);
}
static int fts_numlen(int n)
{
int result;
result = 1;
if (n < 0)
{
n *= -1;
result++;
}
while (n)
{
n /= 10;
if (n)
result++;
}
return (result);
}
static char *fts_strproc(char *s, int n)
{
char *scpy;
int negative;
scpy = s;
negative = 0;
if (n == 0)
*s++ = '0';
else if (n < 0)
{
if (n == -2147483648)
{
ft_strlcpy(s, "-2147483648", 12);
return (s);
}
negative = 1;
n *= -1;
}
while (n)
{
*s++ = n % 10 + '0';
n /= 10;
}
if (negative)
*s++ = '-';
return (fts_strrev(scpy, ft_strlen(scpy)));
}
static char *fts_strrev(char *s, size_t len)
{
size_t i;
char temp;
i = -1;
while (++i < len / 2)
{
temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
return (s);
}