libft
Loading...
Searching...
No Matches
ft_itoa.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_itoa.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tspoof <tspoof@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2022/11/05 18:54:42 by tspoof #+# #+# */
9/* Updated: 2022/11/30 16:47:36 by tspoof ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "libft.h"
14
15static int ft_itoa_size(long num)
16{
17 int i;
18
19 i = 1;
20 if (num < 0)
21 {
22 num = num * -1;
23 i++;
24 }
25 while (num >= 10)
26 {
27 num = num / 10;
28 i++;
29 }
30 return (i);
31}
32
33static char *ft_itoa_rec(long num, int sign, char *str)
34{
35 static int i = 1;
36 int current_i;
37
38 current_i = i;
39 if (num >= 10)
40 {
41 i++;
42 ft_itoa_rec(num / 10, sign, str);
43 }
44 if (num < 10)
45 {
46 if (sign == -1 && str)
47 {
48 str[0] = '-';
49 i++;
50 }
51 }
52 if (str)
53 str[i - current_i] = num % 10 + '0';
54 return (str);
55}
56
57char *ft_itoa(int n)
58{
59 char *str;
60 long num;
61 int sign;
62
63 sign = 1;
64 num = n;
65 str = (char *)ft_calloc(ft_itoa_size(num) + 1, sizeof(char));
66 if (!str)
67 return (NULL);
68 if (num < 0)
69 {
70 num = num * -1;
71 sign = -1;
72 }
73 str = ft_itoa_rec(num, sign, str);
74 return (str);
75}
char * ft_itoa(int n)
Integer to ASCII.
Definition ft_itoa.c:57
void * ft_calloc(size_t count, size_t size)
Allocate and zero.
Definition ft_calloc.c:15