-
Notifications
You must be signed in to change notification settings - Fork 12
/
ft_itoa.c
51 lines (47 loc) · 1.55 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apuchill <apuchill@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/13 15:23:36 by exam #+# #+# */
/* Updated: 2020/02/19 14:03:51 by apuchill ### ########.fr */
/* */
/* ************************************************************************** */
/*
** LIBRARY: N/A
** SYNOPSIS: convert integer to ASCII string
**
** DESCRIPTION:
** Allocates (with malloc(3)) and returns a string representing the
** integer received as an argument. Negative numbers must be handled.
*/
#include "libft.h"
char *ft_itoa(int n)
{
char *str;
long nbr;
size_t size;
nbr = n;
size = n > 0 ? 0 : 1;
nbr = nbr > 0 ? nbr : -nbr;
while (n)
{
n /= 10;
size++;
}
if (!(str = (char *)malloc(size + 1)))
return (0);
*(str + size--) = '\0';
while (nbr > 0)
{
*(str + size--) = nbr % 10 + '0';
nbr /= 10;
}
if (size == 0 && str[1] == '\0')
*(str + size) = '0';
else if (size == 0 && str[1] != '\0')
*(str + size) = '-';
return (str);
}