ft_itoa_base.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* ft_itoa_base.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: ll-hotel <ll-hotel@student.42lyon.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/03/17 16:39:32 by ll-hotel #+# #+# */ 9 /* Updated: 2024/08/20 17:49:22 by ll-hotel ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "ft_basics.h" 14 #include "ft_math.h" 15 16 char *ft_itoa_base(int n, const char *base_a) 17 { 18 const unsigned char is_negative = (n < 0); 19 const unsigned char base = ft_strlen(base_a); 20 char *n_a; 21 long tmp; 22 short i; 23 24 i = ft_log_b(n, base) + 1; 25 n_a = ft_calloc(i + 1 + is_negative, sizeof(char)); 26 if (!n_a) 27 return (0); 28 i += is_negative; 29 tmp = n * (!is_negative - is_negative); 30 while (i-- > is_negative) 31 { 32 n_a[i] = base_a[tmp % base]; 33 tmp /= base; 34 } 35 if (is_negative) 36 n_a[0] = '-'; 37 return (n_a); 38 }