-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
87 lines (78 loc) · 1.94 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: mgraf <mgraf@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/09 15:39:50 by mgraf #+# #+# */
/* Updated: 2022/12/12 19:00:24 by mgraf ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_i_len(int n)
{
int len;
len = 0;
while (n != 0)
{
n /= 10;
len++;
}
return (len);
}
static char *ft_i_special(void)
{
char *s;
s = ft_calloc(12, sizeof(char));
if (!s)
return (NULL);
ft_memcpy(s, "-2147483648", 11);
return (s);
}
/**
* @brief Converts an integer to a string.
*
* This function converts the integer passed as argument to a string
* representation.
*
* @param n The integer to be converted.
*
* @return The string representation of the integer passed as argument.
* NULL if the allocation fails.
*/
char *ft_itoa(int n)
{
char *s;
int len;
len = ft_i_len(n);
if (n == -2147483648)
return (ft_i_special());
if (n < 0 || n == 0)
len++;
s = ft_calloc(len + 1, sizeof(char));
if (!s)
return (NULL);
if (n < 0)
{
n = -n;
s[0] = '-';
}
while (n / 10 != 0)
{
s[len - 1] = (n % 10) + '0';
n /= 10;
len--;
}
s[len - 1] = n + '0';
return (s);
}
// int main(void)
// {
// int n;
// char *s;
// n = -88;
// s = ft_itoa(n);
// printf("String is: '%s'\n", s);
// free(s);
// }