-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprint_bin.c
84 lines (66 loc) · 1.23 KB
/
print_bin.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
#include "main.h"
#include <limits.h>
/**
* rever_binary - fills the array from right to left
* with the binary value of the number
* @binary: array of memory
* @size: size of binary memory in byte
* or positive
* @quotient: the number in decimal value
* and positive
* Return: array of binary number
*/
char *rever_binary(char *binary, unsigned int quotient, int size)
{
int i;
for (i = 0; i < size; i++)
binary[i] = '0';
binary[i] = '\0';
for (i = size - 1; quotient > 1; i--)
{
if (quotient % 2 != 0)
binary[i] = '1';
quotient /= 2;
}
if (quotient != 0)
binary[i] = '1';
return (binary);
}
/**
* print_bin - prints unsigned int
* in binary format
*
* @args: arguments
* @buffer: the pointer
*
* Return: number of printed int
*/
int print_bin(va_list args, char *buffer)
{
int num;
unsigned int quotient, a;
int size = 0;
char *binary;
num = va_arg(args, int);
if (num == 0)
{
buffer[0] = '0';
_print_buf(buffer, 1);
return (1);
}
else
quotient = num;
a = quotient;
while (a > 0)
{
a /= 2;
size++;
}
binary = malloc(sizeof(char) * (size + 1));
if (binary == NULL)
return (-1);
rever_binary(binary, quotient, size);
_print_buf(binary, size);
free(binary);
return (size);
}