-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
72 lines (64 loc) · 1.82 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nopereir <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/23 22:42:28 by nopereir #+# #+# */
/* Updated: 2022/06/29 18:53:49 by nopereir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_numlen(int num);
static int ft_isnegative(int n);
static char *ft_convert_itoa(char *str, size_t size, unsigned int num,
unsigned int is_negative);
char *ft_itoa(int n)
{
size_t digits;
unsigned int is_negative;
unsigned int nb;
char *str;
digits = ft_numlen(n);
is_negative = ft_isnegative(n);
if (is_negative)
nb = -n;
else
nb = n;
str = malloc(sizeof(char) * (digits + 1));
if (str == NULL)
return (NULL);
return (ft_convert_itoa(str, digits, nb, is_negative));
}
static int ft_isnegative(int n)
{
return (n < 0);
}
static int ft_numlen(int num)
{
size_t len;
len = 1;
if (num < 0)
len++;
num /= 10;
while (num)
{
num /= 10;
len++;
}
return (len);
}
static char *ft_convert_itoa(char *str, size_t size, unsigned int num,
unsigned int is_negative)
{
str[size] = '\0';
while (size--)
{
str[size] = (num % 10) + 48;
num /= 10;
}
if (is_negative)
str[0] = '-';
return (str);
}