This repository has been archived by the owner on Nov 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft_itoa.c
78 lines (70 loc) · 1.74 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcombeau <mcombeau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 18:04:16 by mcombeau #+# #+# */
/* Updated: 2021/12/08 12:12:23 by mcombeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION :
The function ft_itoa converts the integer n into a string of characters.
RESULT VALUE :
The string of the converted integer.
*/
static size_t ft_itoa_len(long num)
{
size_t len;
len = 0;
if (num == 0)
return (1);
if (num < 0)
{
len++;
num = -num;
}
while (num >= 1)
{
len++;
num /= 10;
}
return (len);
}
static char *ft_num_to_str(long num, char *str, size_t len)
{
str = ft_calloc(len + 1, sizeof(char));
if (str == NULL)
return (NULL);
if (num < 0)
{
str[0] = '-';
num = -num;
}
len--;
while (len)
{
str[len] = (num % 10) + '0';
num /= 10;
len--;
}
if (str[0] != '-')
str[0] = (num % 10) + '0';
return (str);
}
char *ft_itoa(int n)
{
long num;
size_t len;
char *str;
num = n;
len = ft_itoa_len(num);
str = 0;
str = ft_num_to_str(num, str, len);
if (!str)
return (NULL);
return (str);
}