tgrekov-libft
HIVE libft Oct 2023
Loading...
Searching...
No Matches
ft_itoa.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_itoa.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2023/10/27 20:57:54 by tgrekov #+# #+# */
9/* Updated: 2023/11/09 20:12:57 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include "libft.h"
21
22static int int_length(int n)
23{
24 int i;
25
26 i = 0;
27 while (n)
28 {
29 n /= 10;
30 i++;
31 }
32 return (i);
33}
34
35static char *edge_case(int n)
36{
37 if (!n)
38 return (ft_strdup("0"));
39 return (ft_strdup("-2147483648"));
40}
41
50char *ft_itoa(int n)
51{
52 int len;
53 char negative;
54 char *str;
55
56 if (!n || n == -2147483648)
57 return (edge_case(n));
58 negative = 0;
59 if (n < 0)
60 {
61 n = -n;
62 negative = 1;
63 }
64 len = int_length(n);
65 str = ft_calloc(negative + len + 1, 1);
66 if (!str)
67 return (0);
68 if (negative)
69 str[0] = '-';
70 while (n)
71 {
72 str[negative + len-- - 1] = n % 10 + '0';
73 n /= 10;
74 }
75 return (str);
76}
void * ft_calloc(size_t count, size_t size)
Allocates count * size bytes with malloc and returns a pointer to the result.
Definition ft_calloc.c:34
char * ft_itoa(int n)
Converts integer n to an allocated ASCII string.
Definition ft_itoa.c:50
char * ft_strdup(const char *s1)
Allocates memory for, copies to, and returns a duplicate of s1.
Definition ft_strdup.c:28