Libft
42 Libft library documentation
Loading...
Searching...
No Matches
ft_itoa.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_itoa.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: raphalme <raphalme@student.42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2025/12/29 19:06:00 by raphalme #+# #+# */
9/* Updated: 2026/04/14 10:45:22 by raphalme ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include <stdlib.h>
14
15static size_t ft_num_len(int n);
16
23char *ft_itoa(int n)
24{
25 char *str;
26 size_t len;
27 unsigned int nb;
28
29 len = ft_num_len(n);
30 str = (char *)malloc(sizeof(char) * (len + 1));
31 if (!str)
32 return (NULL);
33 str[len] = '\0';
34 if (n < 0)
35 {
36 str[0] = '-';
37 nb = -n;
38 }
39 else
40 nb = n;
41 if (nb == 0)
42 str[0] = '0';
43 while (nb != 0)
44 {
45 str[--len] = (nb % 10) + '0';
46 nb /= 10;
47 }
48 return (str);
49}
50
59static size_t ft_num_len(int n)
60{
61 size_t len;
62
63 len = 0;
64 if (n <= 0)
65 len++;
66 while (n != 0)
67 {
68 n /= 10;
69 len++;
70 }
71 return (len);
72}
static size_t ft_num_len(int n)
Computes the number of characters needed for an int string.
Definition ft_itoa.c:59
char * ft_itoa(int n)
Converts an integer to a newly allocated decimal string.
Definition ft_itoa.c:23