예제 #1
0
파일: ft_itoa.c 프로젝트: mamwalou/libft
static int	nblen(int n)
{
	if (n < 0)
		return (1 + nblen(-n));
	if (n < 10)
		return (1);
	return (1 + nblen(n / 10));
}
예제 #2
0
파일: ft_itoa.c 프로젝트: mamwalou/libft
char		*ft_itoa(int n)
{
	int		len;
	int		neg;
	int		i;
	char	*str;

	if (n == -2147483648)
		return (ft_strdup("-2147483648"));
	neg = (n < 0 ? 1 : 0);
	len = nblen(n);
	str = (char*)malloc(sizeof(*str) * (len + 1));
	if (str)
	{
		n = (n < 0 ? -n : n);
		i = len - 1;
		while (i >= neg)
		{
			str[i] = (n % 10) + 48;
			n /= 10;
			i--;
		}
		if (neg)
			str[0] = '-';
		str[len] = '\0';
	}
	return (str);
}
예제 #3
0
파일: ft_itoa_base.c 프로젝트: koloux/libft
char	*ft_itoa_base(int value, int base)
{
	char	*res;
	int	flag;
	size_t	size;
	int	i;

	if (value == 0)
		return (ft_strdup("0"));
	else if (value == -2147483648)
		return (ft_strdup("-2147483648")); 
	else
	{
		flag = (value < 0) ? 1 : 0;
		size = nblen(value, base);
		if(!(res = (char *)ft_memalloc(size + flag + 1)))
			return (NULL);
		i = (int)size + flag - 1;
		while (value != 0)
		{
			res[i] = hex(value % base);
			value /= base;
			i--;
		}
		res[i] = (flag == 1) ? '-' : res[i];
		res[size] = '\0';
	}
	return (res);
}