Skip to content

Instantly share code, notes, and snippets.

@yclim95
Last active June 6, 2022 00:00
Show Gist options
  • Save yclim95/0bc4532f95d878a97c47bd355bbe92e2 to your computer and use it in GitHub Desktop.
Save yclim95/0bc4532f95d878a97c47bd355bbe92e2 to your computer and use it in GitHub Desktop.
ft_itoa() in c
#include <stdio.h>
#include <stdlib.h>

size_t	ft_strlen(const char *s)
{
	size_t len;

	len = 0;
	while (*s++)
		len++;
	return (len);
}

char	*ft_strdup(const char *s)
{
	size_t	slen;
	char	*result;

	slen = ft_strlen(s);
	if (!(result = (char *)malloc(sizeof(char) * (slen + 1))))
		return (0);
	slen = 0;
	while (s[slen])
	{
		result[slen] = s[slen];
		slen++;
	}
	result[slen] = '\0';
	return (result);
}

static void		ft_put_nbr(char *dest, unsigned int n)
{
	if (n < 10)
	{
		*dest = n + '0'; // Print number [0 - 9] : Ex [15] : 1 dest = {1 , 5}
		printf("*dest (< 10): %s\n", dest);
	}
	else
	{
		*dest = n % 10 + '0'; // Ex: [15] : 5
		printf("*dest (> 10): %s\n", dest);
		ft_put_nbr(dest - 1, n / 10); // Ex: [15] : 1  dest = { , 5}
	}
}

static size_t	ft_num_len(int n)
{
	size_t c;

	c = 0;
	while (n)
	{
		n /= 10;
		c++;
	}
	return (c);
}

char			*ft_itoa(int n)
{
	size_t			len;
	unsigned int	num;
	char			*pt_itoa;

	num = n;
	if (n == 0)
		return (ft_strdup("0"));
	else
	{
	    if (n < 0)
	        len = ft_num_len(n) + 1; // count number of digits
	    else
	        len = ft_num_len(n);
	   pt_itoa = malloc(sizeof(char) * (len + 1));
		if (!pt_itoa)
			return (0);
		if (n < 0)
		    num = -num;
		else
		    num = num;
		ft_put_nbr(pt_itoa + len - 1, num); // negative ( + len - 1)
		
		if (n < 0)
			*pt_itoa = '-';
		pt_itoa[len] = '\0';
	}
	return (pt_itoa);
}

int main()
{
    char *pt_itoa1 = ft_itoa(5);
    char *pt_itoa2 = ft_itoa(-5);
    char *pt_itoa3 = ft_itoa(0);
    char *pt_itoa4 = ft_itoa(15);
    printf("itoa1: %s\n", pt_itoa1);
    printf("itoa2: %s\n", pt_itoa2);
    printf("itoa3: %s\n", pt_itoa3);
    printf("itoa4: %s\n", pt_itoa4);

    return 0;
}
*dest (< 10): 5
*dest (< 10): 5
*dest (> 10): 5
*dest (< 10): 15
itoa1: 5
itoa2: -5
itoa3: 0
itoa4: 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment