diff options
| author | Charles <sircharlesaze@gmail.com> | 2019-10-25 04:08:13 +0200 |
|---|---|---|
| committer | Charles <sircharlesaze@gmail.com> | 2019-10-25 04:08:13 +0200 |
| commit | 70b928b3ee9a1de7769531edd82c0b43cf6d4d84 (patch) | |
| tree | abf169e7b2ee86fe9d3fe6d34ba131ef4b3c2752 | |
| parent | cade8c9ab269b0981725f002fea34fda035fb707 (diff) | |
| download | libft-70b928b3ee9a1de7769531edd82c0b43cf6d4d84.tar.gz libft-70b928b3ee9a1de7769531edd82c0b43cf6d4d84.tar.bz2 libft-70b928b3ee9a1de7769531edd82c0b43cf6d4d84.zip | |
Added ft_itoa_base
| -rw-r--r-- | ft_itoa_base.c | 56 | ||||
| -rw-r--r-- | libft.h | 3 |
2 files changed, 58 insertions, 1 deletions
diff --git a/ft_itoa_base.c b/ft_itoa_base.c new file mode 100644 index 0000000..9f65422 --- /dev/null +++ b/ft_itoa_base.c @@ -0,0 +1,56 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_itoa_base.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2019/10/25 04:00:58 by cacharle #+# #+# */ +/* Updated: 2019/10/25 04:07:42 by cacharle ### ########.fr */ +/* */ +/* ************************************************************************** */ + +static int nbrlen_radix(long int nbr, int radix) +{ + int counter; + long unsigned int u_nbr; + + if (nbr == 0) + return (1); + counter = 0; + u_nbr = nbr; + if (nbr < 0) + { + counter++; + u_nbr = -nbr; + } + while (u_nbr > 0) + { + u_nbr /= radix; + counter++; + } + return (counter); +} + +char *ft_itoa_base(long int n, char *base) +{ + char *str; + int len; + int radix; + long unsigned int u_nbr; + + radix = ft_strlen(base); + len = nbrlen_radix(n, radix); + if ((str = (char*)malloc(sizeof(char) * (len + 1))) == NULL) + return (NULL); + str[len] = '\0'; + u_nbr = n < 0 ? -n : n; + if (n < 0) + str[0] = '-'; + while (--len >= (n < 0 ? 1 : 0)) + { + str[len] = base[u_nbr % radix]; + u_nbr /= radix; + } + return (str); +} @@ -6,7 +6,7 @@ /* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/07 09:45:02 by cacharle #+# #+# */ -/* Updated: 2019/10/25 03:32:43 by cacharle ### ########.fr */ +/* Updated: 2019/10/25 04:03:57 by cacharle ### ########.fr */ /* */ /* ************************************************************************** */ @@ -82,6 +82,7 @@ void ft_putstr_fd(char *s, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); char *ft_strndup(const char *s1, size_t n); +char *ft_itoa_base(long int n, char *base); /* ** bonus |
