From: Lukas Jiriste Date: Fri, 15 Sep 2023 16:48:24 +0000 (+0200) Subject: Added the function itoa_base fr unsigned integers. Changed libft.h accordingly. X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=ddbbb7c8475d0ea607f847ddfba7e094217d7333;p=Libft.git Added the function itoa_base fr unsigned integers. Changed libft.h accordingly. --- diff --git a/ft_uitoa_base.c b/ft_uitoa_base.c new file mode 100644 index 0000000..3d446c2 --- /dev/null +++ b/ft_uitoa_base.c @@ -0,0 +1,73 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_uitoa_base.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: ljiriste +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2023/09/05 09:46:11 by ljiriste #+# #+# */ +/* Updated: 2023/09/15 18:43:25 by ljiriste ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include //malloc +#include //intmax_t +#include "libft.h" + +static int size_needed(uintmax_t n, size_t base_len) +{ + int res; + + if (n == 0) + return (2); + res = 1; + while (n != 0) + { + ++res; + n /= base_len; + } + return (res); +} + +static int valid_base(const char *base) +{ + int i; + int j; + + if (ft_strlen(base) < 2) + return (0); + i = 0; + while (base[i]) + { + j = i + 1; + while (base[j]) + if (base[i] == base[j++]) + return (0); + ++i; + } + return (1); +} + +char *ft_uitoa_base(uintmax_t n, const char *base) +{ + int size; + int base_len; + char *res; + + if (!valid_base(base)) + return (NULL); + base_len = ft_strlen(base); + size = size_needed(n, base_len); + res = malloc(size); + if (res == NULL) + return (res); + res[--size] = '\0'; + if (n == 0) + res[0] = base[0]; + while (n != 0) + { + res[--size] = base[n % base_len]; + n /= base_len; + } + return (res); +} diff --git a/libft.h b/libft.h index c837206..2a9f9ec 100644 --- a/libft.h +++ b/libft.h @@ -6,7 +6,7 @@ /* By: ljiriste +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/15 12:58:15 by ljiriste #+# #+# */ -/* Updated: 2023/09/05 12:06:26 by ljiriste ### ########.fr */ +/* Updated: 2023/09/15 18:43:23 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ @@ -57,6 +57,7 @@ char **ft_split(const char *s, char c); char *ft_itoa(int n); char *ft_itoa_base(intmax_t n, const char *base); +char *ft_uitoa_base(uintmax_t n, const char *base); char *ft_ctoa(char c); char *ft_strmapi(const char *s, char (*f)(unsigned int, char));