-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
60 lines (55 loc) · 1.62 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmachado <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/10 17:54:54 by gmachado #+# #+# */
/* Updated: 2022/04/20 14:40:38 by gmachado ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#define MAX_CHARS 10
static char *copy_from_buffer(char *buffer, int end_pos, int is_negative)
{
int idx;
char *result;
idx = 0;
result = (char *)malloc((end_pos + is_negative + 1) * sizeof(char));
if (result == NULL)
return (NULL);
if (is_negative)
{
result[idx++] = '-';
}
while (end_pos-- > 0)
{
result[idx++] = buffer[end_pos];
}
result[idx] = '\0';
return (result);
}
char *ft_itoa(int n)
{
char buffer[MAX_CHARS];
int end_pos;
int is_negative;
end_pos = 0;
is_negative = 0;
if (n == 0)
buffer[end_pos++] = '0';
else
{
if (n > 0)
n = -n;
else
is_negative = 1;
while (n != 0)
{
buffer[end_pos++] = '0' - n % 10;
n /= 10;
}
}
return (copy_from_buffer(buffer, end_pos, is_negative));
}