minishell/libft/libft/ft_itoa.c
2025-02-12 15:12:42 +01:00

90 lines
2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jguelen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/18 16:29:21 by jguelen #+# #+# */
/* Updated: 2024/10/23 09:15:57 by jguelen ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
/*Returns the size of the string needed to represent n in base 10 as a string*/
/* DOES NOT INCLUDE THE NULL BYTE*/
static size_t ft_itolen(int n)
{
size_t i;
int calc;
i = 0;
calc = n;
if (n == 0)
return (1);
while (calc != 0)
{
calc /= 10;
i++;
}
if (n > 0)
return (i);
return (i + 1);
}
char *ft_itoa(int n)
{
char *arg;
int calc;
size_t len;
calc = n;
len = ft_itolen(n);
arg = (char *)malloc((len + 1) * sizeof(char));
if (arg == NULL)
return (NULL);
arg[len--] = '\0';
if (calc == 0)
arg[0] = '0';
if (calc < 0)
{
arg[0] = '-';
arg[len--] = (-1 * (calc % 10)) + '0';
calc /= -10;
}
while (calc > 0)
{
arg[len--] = calc % 10 + '0';
calc /= 10;
}
return (arg);
}
/*
int main(void)
{
int i;
char *s;
i = -2147483648;
i = (-1 * (i % 10));
printf("Test op : %d\n", i);
i = -2147483648;
s = ft_itoa(i);
printf("%s\n", s);
free(s);
i = -2;
s = ft_itoa(i);
printf("%s\n", s);
free(s);
i = 2147483647;
s = ft_itoa(i);
printf("%s\n", s);
free(s);
i = 0;
s = ft_itoa(i);
printf("%s\n", s);
free(s);
return (0);
}*/