-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_ptr_to_hex.c
75 lines (68 loc) · 1.89 KB
/
ft_ptr_to_hex.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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_ptr_to_hex.c :+: :+: */
/* +:+ */
/* By: splattje <[email protected]> +#+ */
/* +#+ */
/* Created: 2023/11/07 14:15:49 by splattje #+# #+# */
/* Updated: 2023/11/14 16:54:41 by splattje ######## odam.nl */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static int count_hex_digits(void *ptr)
{
unsigned long long intptr;
int count;
intptr = (unsigned long long)ptr;
count = 0;
while (intptr > 0)
{
intptr >>= 4;
count++;
}
if (count > 0)
return (count);
else
return (1);
}
static char *reverse(char *str, int size)
{
int i;
int length;
char temp;
i = 0;
length = size / 2;
while (i < length)
{
temp = str[i];
str[i] = str[size - i - 1];
str[size - i - 1] = temp;
i++;
}
return (str);
}
char *ptr_to_hex(void *ptr)
{
int buffer_size;
char *hex_buffer;
int i;
unsigned long long digit;
buffer_size = count_hex_digits(ptr) + 1;
hex_buffer = (char *)malloc(buffer_size);
i = 0;
while (1)
{
digit = (unsigned long long)ptr & 0xF;
ptr = (void *)((unsigned long long)ptr >> 4);
if (digit < 10)
hex_buffer[i++] = '0' + digit;
else
hex_buffer[i++] = 'a' + (digit - 10);
if ((unsigned long long)ptr == 0)
break ;
}
hex_buffer[i] = '\0';
hex_buffer = reverse(hex_buffer, i);
return (hex_buffer);
}