-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
55 lines (50 loc) · 1.43 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jode-vri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/06 21:57:20 by jode-vri #+# #+# */
/* Updated: 2020/11/16 15:15:55 by jode-vri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int get_length(unsigned int n)
{
unsigned int i;
i = 0;
while (n >= 10)
{
n /= 10;
i++;
}
return (i + 1);
}
char *ft_itoa(int n)
{
char *dest;
unsigned int len;
unsigned int nb;
unsigned int i;
nb = (n < 0 ? -n : n);
len = get_length(nb);
i = 0;
if (!(dest = (char *)malloc(sizeof(char) * len + 1 + (n < 0 ? 1 : 0))))
return (NULL);
if (n < 0)
{
dest[i] = '-';
len++;
}
i = len - 1;
while (nb >= 10)
{
dest[i] = nb % 10 + '0';
nb /= 10;
i--;
}
dest[i] = nb % 10 + '0';
dest[len] = '\0';
return (dest);
}