-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb_p_specifiers.c
105 lines (96 loc) · 2.2 KB
/
b_p_specifiers.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
#include "main.h"
/**
* custom_b_handler - Handles a custom %b format specifier
* Description: The %b format specifier coverts an unsigned int argument
* to binary
* @ap: Argument pointer
* @count: A pointer to the number of printed characters
* @total: A pointer to the total number of characters printed
* @buffer: A pointer to the buffer holding the characters to be printed
* @field_width: The field width
*/
void custom_b_handler(va_list ap, int *count, int *total, char *buffer,
int field_width)
{
unsigned int number;
char bin[CHAR_BIT * sizeof(unsigned int)];
int i, j;
UNUSED(field_width);
number = va_arg(ap, unsigned int);
if (number == 0)
{
buffer[*count] = '0';
(*count)++;
if (*count == 1024)
{
*total += write(1, (const void *)buffer, *count);
*count = 0;
}
return;
}
if (number > 0)
{
i = 0;
while (number > 0)
{
bin[i++] = (number % 2) + '0';
number /= 2;
}
for (j = i - 1; j >= 0; j--)
{
buffer[*count] = bin[j];
(*count)++;
if (*count == 1024)
{
*total += write(1, (const void *)buffer, *count);
*count = 0;
}
}
}
}
#include "main.h"
/**
* ptr_format_handler - Handles the %p format specifier
* @ap: Argument pointer
* @count: A pointer to the number of printed characters
* @total: A pointer to the total number of characters printed
* @buffer: A pointer to the buffer holding the characters to be printed
* @field_width: The field width
*/
void ptr_format_handler(va_list ap, int *count, int *total, char *buffer,
int field_width)
{
void *ptr = va_arg(ap, void *);
char hexa_chars[] = "0123456789abcdef";
char hexa_buffer[2048];
int i = 0, j;
unsigned long num = (unsigned long)ptr;
if (ptr == NULL)
{
buffer[(*count)++] = '(';
buffer[(*count)++] = 'n';
buffer[(*count)++] = 'i';
buffer[(*count)++] = 'l';
buffer[(*count)++] = ')';
}
else
{
while (num != 0)
{
hexa_buffer[i++] = hexa_chars[num % 16];
num /= 16;
}
}
hexa_buffer[i++] = 'x';
hexa_buffer[i++] = '0';
if (field_width > 0)
{
field_width -= i;
field_width_handler(field_width, buffer, count, total);
}
for (j = i - 1; j >= 0; j--)
{
buffer[(*count)++] = hexa_buffer[j];
buffer_status_handler(count, total, buffer);
}
}