-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_hex_utils.c
115 lines (107 loc) · 2.49 KB
/
ft_hex_utils.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_hex_utils.c :+: :+: */
/* +:+ */
/* By: jvan-hal <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/10/27 09:14:16 by jvan-hal #+# #+# */
/* Updated: 2023/01/11 10:57:20 by jvan-hal ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static int getlength(unsigned long int n, t_padding *padinfo)
{
int count;
count = 0;
if (padinfo->prec > -1)
padinfo->padc = ' ';
if (padinfo->prec == 0 && n == 0)
return (0);
if (padinfo->alt == 'y' && padinfo->padc == '0' && n > 0)
padinfo->width -= 2;
while ((n / 16) > 0)
{
++count;
n /= 16;
}
if (n < 16)
++count;
if (count < padinfo->prec)
count = padinfo->prec;
if (padinfo->padc == '0' && padinfo->prec == -1 && padinfo->width > count)
{
padinfo->prec += (padinfo->width - count);
count = padinfo->width;
}
return (count);
}
static char gethexchar(int n, char type)
{
if (n < 10)
{
return (n + '0');
}
else
{
if (type == 'x')
return (n - 10 + 'a');
else if (type == 'X')
return (n - 10 + 'A');
}
return ('~');
}
char *getstr_ptr(uintptr_t ptr, char type, t_padding *padinfo)
{
int i;
char *c;
i = getlength(ptr, padinfo) + 2;
c = ft_calloc(i + 1, 1);
if (!c)
return (NULL);
--i;
while (ptr >= 16)
{
c[i] = gethexchar((ptr % 16), type);
ptr /= 16;
--i;
}
c[i] = gethexchar((ptr % 16), type);
--i;
while (i > 1)
{
c[i] = '0';
--i;
}
c[i] = type;
--i;
c[i] = '0';
return (c);
}
char *getstr_hex(long long int n, char type, t_padding *padinfo)
{
int i;
char *c;
if (n < 0)
n = ((2147483648 + n) * 2) - n;
if (padinfo->alt == 'y' && n > 0)
return (getstr_ptr(n, type, padinfo));
i = getlength(n, padinfo);
c = ft_calloc(i + 1, 1);
if (!c)
return (NULL);
--i;
while (n >= 16)
{
c[i] = gethexchar((n % 16), type);
n /= 16;
--i;
}
c[i] = gethexchar((n % 16), type);
while (i > 0)
{
--i;
c[i] = '0';
}
return (c);
}