-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintf_b.c
More file actions
46 lines (39 loc) · 747 Bytes
/
printf_b.c
File metadata and controls
46 lines (39 loc) · 747 Bytes
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
#include "main.h"
/**
* printf_b - prints binary numbers (unsigned)
* @args: the number
*
* Return: number of chars printed
*/
int printf_b(va_list args)
{
int count = 0;
unsigned int decimalNumber = va_arg(args, unsigned int);
int i = 1, retval;
char *string;
if (decimalNumber < 1)
{
_putchar(0 + '0');
return (1);
}
count += countBinary(decimalNumber);
string = malloc(sizeof(char) * (count + 1));
if (string == NULL)
return (-1);
for (i = 1; i < count + 1; i++)
{
string[count - i] = decimalNumber % 2;
decimalNumber = decimalNumber / 2;
}
for (i = 0; i < count; i++)
{
retval = _putchar(string[i] + '0');
if (retval == -1)
{
free(string);
return (-1);
}
}
free(string);
return (count);
}