-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_tohex_ptr.c
94 lines (85 loc) · 2.23 KB
/
ft_tohex_ptr.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_tohex_ptr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: samoreno <samoreno@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/15 09:08:05 by samoreno #+# #+# */
/* Updated: 2021/12/15 10:56:19 by samoreno ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void ft_fill(unsigned long decimal, char *in_hex);
static char *ft_reverse(char *str);
static void ft_prefix(char *str);
char *ft_tohex_ptr(unsigned long decimal)
{
int size;
unsigned long copy;
char *in_hex;
size = 0;
copy = decimal;
while (copy % 10 != 0 || copy / 10 != 0)
{
size++;
copy /= 10;
}
if (decimal == 0)
in_hex = malloc(sizeof(char) * 2);
else
in_hex = malloc(sizeof(char) * (size + 1));
if (!in_hex)
return (NULL);
ft_fill(decimal, in_hex);
return (ft_reverse(in_hex));
}
static void ft_fill(unsigned long decimal, char *in_hex)
{
int iter;
iter = 0;
if (decimal == 0)
{
in_hex[iter] = '0';
iter++;
}
else
{
while (decimal % 16 != 0 || decimal / 16 != 0)
{
if (decimal % 16 < 10)
in_hex[iter] = (decimal % 16) + '0';
else
in_hex[iter] = (decimal % 16) + 87;
decimal /= 16;
iter++;
}
}
in_hex[iter] = 0;
}
static char *ft_reverse(char *str)
{
int iter_rev;
int iter_str;
char *reversed;
reversed = malloc(sizeof(char) * (ft_strlen(str) + 3));
if (!reversed)
return (NULL);
ft_prefix(reversed);
iter_rev = 2;
iter_str = (ft_strlen(str) - 1);
while (iter_str >= 0)
{
reversed[iter_rev] = str[iter_str];
iter_rev++;
iter_str--;
}
reversed[iter_rev] = 0;
free(str);
return (reversed);
}
static void ft_prefix(char *str)
{
str[0] = '0';
str[1] = 'x';
}