Add hexadecimal support w/ ft_itoa_base
This commit is contained in:
79
libftprintf/ft_itoa_base.c
Normal file
79
libftprintf/ft_itoa_base.c
Normal file
@@ -0,0 +1,79 @@
|
||||
/* ************************************************************************** */
|
||||
/* */
|
||||
/* ::: :::::::: */
|
||||
/* ft_itoa_base.c :+: :+: :+: */
|
||||
/* +:+ +:+ +:+ */
|
||||
/* By: gbaconni <gbaconni@42lausanne.ch> +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2021/08/16 13:51:16 by gbaconni #+# #+# */
|
||||
/* Updated: 2022/04/15 00:08:27 by gbaconni ### lausanne.ch */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
#include "libftprintf.h"
|
||||
|
||||
static int ft_intlen_base(int n, int nbase);
|
||||
static char *ft_strrev(char *s);
|
||||
|
||||
char *ft_itoa_base(int n, char *base)
|
||||
{
|
||||
char *s;
|
||||
int i;
|
||||
long nbr;
|
||||
long nbase;
|
||||
|
||||
nbase = ft_strlen(base);
|
||||
s = (char *) ft_calloc((ft_intlen_base(n, nbase) + 1), sizeof(char));
|
||||
if (s == NULL)
|
||||
return (NULL);
|
||||
i = 0;
|
||||
nbr = n;
|
||||
if (nbr == 0)
|
||||
s[i++] = '0';
|
||||
if (nbr < 0)
|
||||
nbr = -nbr;
|
||||
while (nbr > 0)
|
||||
{
|
||||
s[i++] = base[nbr % nbase];
|
||||
nbr /= nbase;
|
||||
}
|
||||
if (n < 0)
|
||||
s[i++] = '-';
|
||||
s[i] = '\0';
|
||||
return (ft_strrev(s));
|
||||
}
|
||||
|
||||
static int ft_intlen_base(int n, int nbase)
|
||||
{
|
||||
size_t len;
|
||||
|
||||
len = 0;
|
||||
if (n < 0 || n == 0)
|
||||
len++;
|
||||
while (!(n < 1 && n > -1))
|
||||
{
|
||||
n /= nbase;
|
||||
len++;
|
||||
}
|
||||
return (len);
|
||||
}
|
||||
|
||||
static char *ft_strrev(char *s)
|
||||
{
|
||||
int len;
|
||||
int i;
|
||||
int j;
|
||||
char c;
|
||||
|
||||
len = ft_strlen(s);
|
||||
i = 0;
|
||||
while (i < (len / 2))
|
||||
{
|
||||
j = len - 1 - i;
|
||||
c = s[i];
|
||||
s[i] = s[j];
|
||||
s[j] = c;
|
||||
i++;
|
||||
}
|
||||
return (s);
|
||||
}
|
||||
Reference in New Issue
Block a user