-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
77 lines (68 loc) · 1.87 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gcosta-d <gcosta-d@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/25 15:00:55 by gcosta-d #+# #+# */
/* Updated: 2021/09/14 10:19:30 by gcosta-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/* Itoa transform an integer in char.
* The return value is the pointer to the first memory
* that was transform. The get_len function count
* the amount of algarisms in n to allocate memory.
*/
static int get_len(int nbr);
static char *get_digit(int n, int n_len, char *str);
char *ft_itoa(int n)
{
char *str;
int n_len;
n_len = get_len(n);
str = (char *) ft_calloc(n_len + 1, sizeof(char));
if (!str)
return (NULL);
if (n == 0)
*str = n / 10 + '0';
else if (n < 0)
{
if (n == -2147483648)
{
ft_strlcpy(str, "-2147483648", n_len + 1);
return (str);
}
str[0] = '-';
n *= -1;
}
str = get_digit(n, n_len, str);
return (str);
}
static int get_len(int nbr)
{
int nbr_len;
nbr_len = 0;
if (nbr <= 0)
nbr_len++;
while (nbr)
{
nbr /= 10;
nbr_len++;
}
return (nbr_len);
}
static char *get_digit(int n, int n_len, char *str)
{
int n1;
n1 = 0;
while (n != 0)
{
n_len--;
n1 = n % 10;
*(str + n_len) = n1 + '0';
n = n / 10;
}
return (str);
}