-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
66 lines (60 loc) · 1.67 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lclerc <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/10 10:04:02 by lclerc #+# #+# */
/* Updated: 2022/11/24 11:25:38 by lclerc ### ########.fr */
/* */
/* ************************************************************************** */
/*
* itoa() converts an integer to a string.
*
* Returns:
* - string of characters
* - NULL if allocation fails
*
* malloc can be used.
*/
#include "libft.h"
int get_length(long n)
{
int length;
length = 0;
if (n == 0)
return (1);
if (n < 0)
length++;
while (n)
{
n = n / 10;
length++;
}
return (length);
}
char *ft_itoa(int n)
{
char *ascii_string;
int length;
long number;
number = n;
length = get_length(number);
ascii_string = (char *)malloc(length * sizeof(char) + 1);
if (!ascii_string)
return (NULL);
ascii_string[length--] = '\0';
if (number < 0)
{
ascii_string[0] = '-';
number = -number;
}
while (number >= 10)
{
ascii_string[length--] = number % 10 + '0';
number = number / 10;
}
ascii_string[length] = number + '0';
return (ascii_string);
}