summaryrefslogtreecommitdiff
path: root/libft/ft_itoa.c
diff options
context:
space:
mode:
Diffstat (limited to 'libft/ft_itoa.c')
-rw-r--r--libft/ft_itoa.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/libft/ft_itoa.c b/libft/ft_itoa.c
new file mode 100644
index 0000000..35c84d1
--- /dev/null
+++ b/libft/ft_itoa.c
@@ -0,0 +1,52 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* ft_itoa.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: kdx <kdx @student.42angouleme.fr +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2022/09/28 19:00:04 by kdx #+# #+# */
+/* Updated: 2022/09/28 19:26:22 by kdx ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "libft.h"
+
+static char *_itoa(long v, int sign, long div, char *ptr)
+{
+ size_t i;
+
+ i = 0;
+ if (sign == -1)
+ ptr[i++] = '-';
+ while (div / 10 > 0)
+ {
+ div /= 10;
+ ptr[i++] = '0' + v / div % 10;
+ }
+ ptr[i] = '\0';
+ return (ptr);
+}
+
+char *ft_itoa(int n)
+{
+ long v;
+ int sign;
+ long div;
+ size_t i;
+ char *ptr;
+
+ if (n == 0)
+ return (ft_strdup("0"));
+ v = n;
+ sign = (v > 0) - (v < 0);
+ v *= sign;
+ div = 1;
+ i = (sign == -1);
+ while (div <= v && ++i)
+ div *= 10;
+ ptr = malloc(i + 1);
+ if (ptr == NULL)
+ return (NULL);
+ return (_itoa(v, sign, div, ptr));
+}