-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
71 lines (63 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lgillot- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/05/12 20:07:21 by lgillot- #+# #+# */
/* Updated: 2015/05/13 18:58:35 by lgillot- ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
static unsigned int nb_chars(long n)
{
unsigned int width;
if (n == 0)
return (1);
width = n < 0 ? 1 : 0;
while (n)
{
n /= 10;
width++;
}
return (width);
}
static char digit_to_char(long n)
{
return ('0' + n);
}
static void apply_sign(long *n, char *s)
{
if (*n < 0)
{
*s = '-';
*n *= -1;
}
}
char *ft_itoa(int n)
{
long big_n;
char *r;
char *it;
big_n = n;
if (big_n == 0)
r = "0";
else
{
r = malloc(nb_chars(big_n) + 1);
if (r)
{
it = r + nb_chars(big_n);
apply_sign(&big_n, r);
*it-- = '\0';
while (big_n)
{
*it-- = digit_to_char(big_n % 10);
big_n /= 10;
}
}
}
return (r);
}