-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
101 lines (90 loc) · 2.2 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: msubtil- <msubtil-@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/19 21:24:13 by msubtil- #+# #+# */
/* Updated: 2022/05/11 22:25:24 by msubtil- ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_int_size(long n)
{
size_t size;
size = 0;
if (n == 0)
return (1);
while (n >= 1)
{
n /= 10;
size++;
}
return (size);
}
static char *ft_allocate_int_str(size_t size, short neg)
{
char *str;
if (neg)
{
str = (char *) malloc(sizeof(char) * (size + 2));
if (str == NULLPTR)
return (NULLPTR);
str[0] = '-';
str[1] = '0';
str[size + 1] = '\0';
return (str + 1);
}
str = (char *) malloc(sizeof(char) * (size + 1));
if (str == NULLPTR)
return (NULLPTR);
str[0] = '0';
str[size] = '\0';
return (str);
}
static void ft_swap_chr(char *p1, char *p2)
{
char tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
static void ft_reverse_str(char *str, size_t size, short neg)
{
size_t index;
index = 0;
while (index < (size / 2))
{
if (neg)
ft_swap_chr(&str[index + 1], &str[size - index]);
else
ft_swap_chr(&str[index], &str[size - index - 1]);
index++;
}
}
char *ft_itoa(int n)
{
long aux_n;
char *str;
size_t size;
aux_n = n;
if (n < 0)
aux_n *= -1;
size = ft_int_size(aux_n);
str = ft_allocate_int_str(size, n < 0);
if (str == NULLPTR)
return (NULLPTR);
while (aux_n >= 1)
{
*str = '0' + (aux_n % 10);
aux_n /= 10.0;
str++;
}
if (n != 0 && n < 0)
str -= (size + 1);
else if (n != 0)
str -= size;
ft_reverse_str(str, size, n < 0);
return (str);
}