-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_printf_utils_conv.c
94 lines (85 loc) · 2.69 KB
/
ft_printf_utils_conv.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_utils_conv.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmarra <gmarra@student.42firenze.it> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/18 15:22:05 by gmarra #+# #+# */
/* Updated: 2024/12/22 16:33:38 by gmarra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *conv_chr(char charnum)
{
char *return_char;
return_char = (char *) malloc(2 * sizeof(char));
if (!return_char)
return (NULL);
return_char[0] = charnum;
return_char[1] = '\0';
return (return_char);
}
static int num_digit(uintptr_t n, unsigned int base)
{
unsigned int digits;
digits = 0;
while (n)
{
digits++;
n = n / base;
}
return (digits);
}
static char *ftpf_itoa(t_convtypenum n, unsigned int base,
unsigned int *flgmask, int format_type)
{
char *str_num;
unsigned int digits;
uintptr_t u_num;
if (!(n.u))
return (ftpf_strdup("0"));
u_num = n.u;
if (n.i < 0 && (format_type == TYPE_D || format_type == TYPE_I))
{
u_num = (uintptr_t) ~ n.i + 1;
set_bit(flgmask, IS_NEG);
}
digits = num_digit(u_num, base);
str_num = (char *) malloc ((digits + 1) * sizeof(char));
if (!str_num)
return (NULL);
ftpf_memset(str_num, 0, digits + 1);
while (digits--)
{
str_num[digits] = u_num % base + '0';
if (str_num[digits] > '9')
str_num[digits] += ('a' - '9' - 1);
u_num = u_num / base;
}
return (str_num);
}
char *convert_arg(int format_type, va_list args, unsigned int *flgmask)
{
char *conv_str;
t_convtypenum value;
unsigned int base;
value.u = 0;
conv_str = NULL;
base = 10;
if (format_type == TYPE_C)
conv_str = conv_chr((char) va_arg(args, int));
else if (format_type == TYPE_S)
conv_str = ftpf_strdup(va_arg(args, char *));
else if (format_type == TYPE_P)
value.u = (uintptr_t)va_arg(args, void *);
else if (format_type == TYPE_D || format_type == TYPE_I)
value.i = va_arg(args, int);
else if (format_type >= TYPE_U)
value.u = (uintptr_t) va_arg(args, unsigned int);
if (format_type == TYPE_P || format_type >= TYPE_X)
base = 16;
if (format_type >= TYPE_P)
conv_str = ftpf_itoa(value, base, flgmask, format_type);
return (conv_str);
}