minishell/libft/ft_printf_hexa.c

74 lines
2.5 KiB
C
Raw Permalink Normal View History

2025-02-12 14:51:05 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_hexa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jguelen <jguelen@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/18 10:39:10 by jguelen #+# #+# */
/* Updated: 2025/02/04 09:52:40 by jguelen ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
/*Presumes base 10 or higher*/
int ft_put_ull_base_fd(unsigned long long n, char *base, int base_size, int fd)
{
unsigned long long calc;
char buf[20];
int i;
if (n == 0)
return (write(fd, "0", 1));
calc = n;
i = 19;
while (calc != 0)
{
buf[i--] = base[calc % base_size];
calc /= base_size;
}
return (write(fd, buf + i + 1, 19 - i));
}
static int ft_printf_hexa2(int fd, t_printf_format *format)
{
if (ft_printf_str(fd, format->prefix, INT_MAX) == -1
|| (format->specifier == PRINTF_HEXA_UPSPEC
&& ft_put_ull_base_fd((unsigned long long)format->var.u,
HEXA_UP, HEX_LEN, fd) == -1))
return (-1);
else if (format->specifier == PRINTF_HEXA_LOWSPEC
&& ft_put_ull_base_fd((unsigned long long)format->var.u,
HEXA_LOW, HEX_LEN, fd) == -1)
return (-1);
return (ft_pad_char(fd, format, " "));
}
int ft_printf_hexa(int fd, t_printf_format *format)
{
int i;
unsigned long long calc;
calc = (unsigned long long)format->var.u;
i = ft_uint_len(calc, HEX_LEN);
if ((format->flags & PRINTF_DOTFLAG) && (format->precision == 0)
&& (format->var.u == 0))
format->total_len = 0;
if ((format->flags & ~PRINTF_MINUSFLAG) == format->flags)
{
if ((format->flags & ~PRINTF_ZEROFLAG) == format->flags
&& ft_pad_char(fd, format, " ") == -1)
return (-1);
else if (ft_pad_char(fd, format, "0") == -1)
return (-1);
}
while (i++ < format->precision)
if (write(fd, "0", 1) == -1)
return (-1);
if ((format->flags & PRINTF_DOTFLAG) && (format->precision == 0)
&& (format->var.u == 0))
return (ft_pad_char(fd, format, " "));
return (ft_printf_hexa2(fd, format));
}