-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_printf_ptr.c
More file actions
88 lines (78 loc) · 2.15 KB
/
ft_printf_ptr.c
File metadata and controls
88 lines (78 loc) · 2.15 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_ptr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dporhomo <dporhomo@student.42prague.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/12/03 23:47:57 by dporhomo #+# #+# */
/* Updated: 2025/12/09 10:29:46 by dporhomo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *ft_ptoa(unsigned long n);
static void ft_fill_ptr(char *str, unsigned long n, int len);
static int ft_format_ptr(char *str, t_flags flags);
int ft_print_ptr(unsigned long n, t_flags flags)
{
char *str;
int count;
if (!n)
{
flags.precision = -1;
return (ft_print_str(PTRNULL, flags));
}
str = ft_ptoa(n);
if (!str)
return (0);
count = ft_format_ptr(str, flags);
free(str);
return (count);
}
static int ft_format_ptr(char *str, t_flags flags)
{
int count;
int len;
count = 0;
len = ft_strlen(str) + 2;
if (flags.left == 0)
count += ft_print_padding(flags.width, len, 0);
count += write(1, "0x", 2);
count += write(1, str, ft_strlen(str));
if (flags.left == 1)
count += ft_print_padding(flags.width, len, 0);
return (count);
}
static char *ft_ptoa(unsigned long n)
{
char *str;
int len;
unsigned long temp;
len = 0;
if (n == 0)
len = 1;
temp = n;
while (temp > 0)
{
temp /= 16;
len++;
}
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (NULL);
ft_fill_ptr(str, n, len);
return (str);
}
static void ft_fill_ptr(char *str, unsigned long n, int len)
{
char *base;
base = "0123456789abcdef";
str[len] = '\0';
if (n == 0)
str[0] = '0';
while (n > 0)
{
str[--len] = base[n % 16];
n /= 16;
}
}