-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_printf_hex.c
More file actions
114 lines (104 loc) · 2.89 KB
/
ft_printf_hex.c
File metadata and controls
114 lines (104 loc) · 2.89 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_hex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dporhomo <dporhomo@student.42prague.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/12/03 22:33:50 by dporhomo #+# #+# */
/* Updated: 2025/12/09 10:27:03 by dporhomo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *ft_xtoa(unsigned int n, int is_upper);
static void ft_xtoa_str(char *str, int len, long num, char *base);
static int ft_format_hex(char *s, t_layout *tab, t_flags f, int up);
static int ft_write_prefix(int is_upper);
int ft_print_hex(unsigned int n, int is_upper, t_flags flags)
{
char *str;
int count;
t_layout tab;
if (n == 0 && flags.precision == 0)
return (ft_print_padding(flags.width, 0, 0));
str = ft_xtoa(n, is_upper);
if (!str)
return (0);
tab.len = ft_strlen(str);
tab.zeros = 0;
if (flags.precision > tab.len)
tab.zeros = flags.precision - tab.len;
tab.sign = (flags.hash && n != 0);
count = ft_format_hex(str, &tab, flags, is_upper);
free(str);
return (count);
}
static char *ft_xtoa(unsigned int n, int is_upper)
{
char *str;
int len;
long num;
char *base;
if (is_upper)
base = "0123456789ABCDEF";
else
base = "0123456789abcdef";
num = n;
if (n == 0)
len = 1;
len = 0;
while (n > 0 || len == 0)
{
n /= 16;
len++;
}
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (NULL);
ft_xtoa_str(str, len, num, base);
return (str);
}
static void ft_xtoa_str(char *str, int len, long num, char *base)
{
str[len] = '\0';
if (num == 0)
str[0] = '0';
while (num > 0)
{
str[--len] = base[num % 16];
num /= 16;
}
}
static int ft_format_hex(char *s, t_layout *tab, t_flags f, int up)
{
int count;
int total;
count = 0;
total = tab->len + tab->zeros + (tab->sign * 2);
if (f.left == 0)
{
if (f.zero && f.precision == -1)
{
if (tab->sign)
count += ft_write_prefix(up);
tab->sign = 0;
count += ft_print_padding(f.width, total, 1);
}
else
count += ft_print_padding(f.width, total, 0);
}
if (tab->sign)
count += ft_write_prefix(up);
while (tab->zeros-- > 0)
count += write(1, "0", 1);
count += write(1, s, tab->len);
if (f.left == 1)
count += ft_print_padding(f.width, total, 0);
return (count);
}
static int ft_write_prefix(int is_upper)
{
if (is_upper)
return (write(1, "0X", 2));
return (write(1, "0x", 2));
}