-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_printf_utils.c
More file actions
105 lines (94 loc) · 2.28 KB
/
Copy pathft_printf_utils.c
File metadata and controls
105 lines (94 loc) · 2.28 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asuc <asuc@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/09 17:53:40 by asuc #+# #+# */
/* Updated: 2023/11/10 18:20:13 by asuc ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/ft_printf.h"
int print_hex(unsigned long nb)
{
char *str;
int ret;
ret = 0;
if (nb == 0)
{
ret = ft_putstr_fd("(nil)", 1);
return (ret);
}
ret += ft_putstr_fd("0x", 1);
str = ft_itoa_base(nb, 16);
ret += ft_putstr_fd(str, 1);
free(str);
return (ret);
}
int ft_num_len_base(unsigned long n, int base)
{
int len;
len = 0;
if (n == 0)
return (1);
while (n)
{
n /= base;
len++;
}
return (len);
}
char *ft_itoa_base(unsigned long n, int base)
{
int len;
char *str;
if (base < 2 || base > 16)
return (NULL);
len = ft_num_len_base(n, base);
str = ft_calloc(sizeof(char), (len + 1));
if (str == NULL)
return (NULL);
len--;
while (len >= 0)
{
str[len] = "0123456789abcdef"[n % base];
n /= base;
len--;
}
return (str);
}
char *ft_itoa_base_hex(unsigned int n, int base, int mode)
{
int len;
char *str;
if (base < 2 || base > 16)
return (NULL);
len = ft_num_len_base(n, base);
str = ft_calloc(sizeof(char), (len + 1));
if (str == NULL)
return (NULL);
len--;
while (len >= 0)
{
if (mode == 3)
str[len] = "0123456789ABCDEF"[n % base];
else
str[len] = "0123456789abcdef"[n % base];
n /= base;
len--;
}
return (str);
}
int print_hex_other(unsigned int nb, int mode)
{
char *str;
int ret;
ret = 0;
if (nb == 0)
return (ft_putstr_fd("0", 1));
str = ft_itoa_base_hex(nb, 16, mode);
ret += ft_putstr_fd(str, 1);
free(str);
return (ret);
}