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.c59
1 files changed, 59 insertions, 0 deletions
diff --git a/libft/ft_itoa.c b/libft/ft_itoa.c
new file mode 100644
index 0000000..09d0319
--- /dev/null
+++ b/libft/ft_itoa.c
@@ -0,0 +1,59 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* ft_itoa.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: kdx <kdx @student.42angouleme.fr +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2022/09/28 19:00:04 by kdx #+# #+# */
+/* Updated: 2022/10/13 22:43:21 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] = '-';
+ i += 1;
+ }
+ while (div / 10 > 0)
+ {
+ div /= 10;
+ ptr[i] = '0' + v / div % 10;
+ i += 1;
+ }
+ 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 + 1)
+ {
+ i += 1;
+ div *= 10;
+ }
+ ptr = malloc(i + 1);
+ if (ptr == NULL)
+ return (NULL);
+ return (_itoa(v, sign, div, ptr));
+}