-
Notifications
You must be signed in to change notification settings - Fork 0
/
itohex.c
63 lines (56 loc) · 1.66 KB
/
itohex.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* itohex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alida-si <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/26 17:40:23 by alida-si #+# #+# */
/* Updated: 2021/11/09 23:20:29 by alida-si ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *n_convert(char *str,
size_t size,
unsigned long int num,
const char format)
{
int result;
str[size] = '\0';
while (size--)
{
result = num % 16;
if (9 < result || result < 16)
str[size] = result + 87;
if (result < 10)
str[size] = result + 48;
num /= 16;
}
if (format == 'X')
strtoupper(str);
return (str);
}
static size_t nb_size(unsigned long int num)
{
size_t len;
len = 1;
num /= 16;
while (num)
{
num /= 16;
len++;
}
return (len);
}
int itohex(unsigned long int n, const char format)
{
size_t n_digits;
char *str;
n_digits = nb_size(n);
str = malloc(sizeof(char) * (n_digits + 1));
if (str == NULL)
return (0);
ft_putstr_fd (n_convert(str, n_digits, n, format), 1);
free (str);
return (n_digits);
}