-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintf_hex_aux.c
executable file
·74 lines (54 loc) · 1.16 KB
/
printf_hex_aux.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
#include "main.h"
/**
* printf_hex_aux - prints hexadecimal representation of a number
* @digit: input number
* Return: number of characters printed
*/
int printf_hex_aux(unsigned long int digit) {
unsigned long int temp;
int counter =0;
long int *array;
int i;
temp = digit;
/**
* Calculate the number of hexadecimal digits required
*/
do {
counter++;
temp /= 16;
}
while (temp != 0);
/**
* Allocate memory for an array to store hexadecimal digits
*/
array = malloc(counter * sizeof(long int));
if (array == NULL) {
return 0;
/**
* Handle memory allocation failure
*/
}
/**
* Populate the array with the hexadecimal digits
*/
for (i = 0; i < counter; i++) {
array[i] = digit % 16;
digit /= 16;
}
/**
* Print the hexadecimal digits in reverse order
*/
for (i = counter - 1; i >= 0; i--) {
char hexDigit;
hexDigit = (array[i] > 9) ? (char)(array[i] + 'a' - 10) : (char)(array[i] + '0');
_putchar(hexDigit);
}
/**
* Free the allocated memory for the array
*/
free(array);
/**
*Return the total count of hexadecimal digits printed
*/
return counter;
}