-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
82 lines (73 loc) · 1.84 KB
/
ft_itoa.c
File metadata and controls
82 lines (73 loc) · 1.84 KB
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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_itoa.c :+: :+: */
/* +:+ */
/* By: pzlatov <pzlatov@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2024/10/23 12:50:24 by pzlatov #+# #+# */
/* Updated: 2024/10/25 20:20:40 by pzlatov ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_digit(long nbr);
static void fill_string(char *nstr, long nbr, size_t len, int is_negative);
char *ft_itoa(int n)
{
long nbr;
char *nstr;
size_t len;
int is_negative;
is_negative = 0;
nbr = n;
if (nbr < 0)
{
is_negative = 1;
nbr = -nbr;
}
len = count_digit(nbr) + is_negative;
nstr = (char *)ft_calloc(len + 1, sizeof(char));
if (!nstr)
{
return (NULL);
}
fill_string(nstr, nbr, len, is_negative);
return (nstr);
}
static size_t count_digit(long nbr)
{
size_t count;
count = 0;
if (nbr == 0)
count ++;
while (nbr > 0)
{
count++;
nbr = nbr / 10;
}
return (count);
}
static void fill_string(char *nstr, long nbr, size_t len, int is_negative)
{
size_t i;
i = len - 1;
if (nbr == 0)
{
nstr[0] = '0';
nstr[1] = '\0';
}
if (is_negative)
{
nstr[0] = '-';
}
while (nbr > 0)
{
nstr[i] = '0' + (nbr % 10);
nbr = nbr / 10;
i--;
}
}
// int main()
// {
// printf("%s", ft_itoa(-2147483648));
// }