aboutsummaryrefslogtreecommitdiffstats
path: root/src/ft_itoa.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/ft_itoa.c')
-rw-r--r--src/ft_itoa.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/ft_itoa.c b/src/ft_itoa.c
new file mode 100644
index 0000000..05f3fae
--- /dev/null
+++ b/src/ft_itoa.c
@@ -0,0 +1,45 @@
+#include "libft.h"
+#include <stdlib.h>
+
+static size_t
+_s_numlen (int n)
+{
+ size_t len;
+
+ len = 1;
+ if (n < 0)
+ len++;
+ while (n / 10)
+ {
+ len++;
+ n /= 10;
+ }
+ return (len);
+}
+
+char *
+ft_itoa (int n)
+{
+ size_t len;
+ char *str;
+ unsigned int nb;
+
+ len = _s_numlen (n);
+ str = malloc (len + 1);
+ if (!str)
+ return (NULL);
+ str[len] = '\0';
+ if (n < 0)
+ {
+ str[0] = '-';
+ nb = -n;
+ }
+ else
+ nb = n;
+ while (len > 0 && str[len - 1] != '-')
+ {
+ str[--len] = '0' + nb % 10;
+ nb /= 10;
+ }
+ return (str);
+}