-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-functions.c
86 lines (80 loc) · 1.63 KB
/
2-functions.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
#include "main.h"
/**
* print_binary - Convertes an integer to binary
*
* @arg_list: Input integers argument (int)
* @buffer: Buffer array (char)
* @index: Number of buffer index (int)
*
* Return: The length of a binary numbers
*/
int print_binary(va_list arg_list, char *buffer, unsigned int index)
{
int number = va_arg(arg_list, int);
int count = 0, i = 0, j = 0, check_negative = 0;
char *binary;
if (number == 0)
{
index = _puts(buffer, '0', index);
return (1);
}
if (number < 0)
{
number = (number * -1) - 1;
check_negative = 1;
}
binary = malloc(sizeof(char) * (32 + 1));
binary = input_to_binary(binary, number, check_negative, 32);
for (; binary[i]; i++)
{
if (j == 0 && binary[i] == '1')
j = 1;
if (j == 1)
{
index = _puts(buffer, binary[i], index);
count++;
}
}
free(binary);
return (count);
}
/**
* input_to_binary - Prints binary numbers
*
* @binary: Input binary format (char)
* @number: Input integers (long int)
* @check_negative: Checks for negative number (int)
* @max_size: Max size for the binary output(int)
*
* Return: The length of a binary numbers
*/
char *input_to_binary(char *binary, long int number,
int check_negative, int max_size)
{
int i = 0;
while (i < max_size)
{
binary[i] = '0';
i++;
}
binary[max_size] = '\0';
for (i = max_size - 1; number > 1; i--)
{
if (number == 2)
binary[i] = '0';
else
binary[i] = (number % 2) + '0';
number /= 2;
}
if (number != 0)
binary[i] = '1';
if (check_negative)
{
for (i = 0; binary[i]; i++)
if (binary[i] == '0')
binary[i] = '1';
else
binary[i] = '0';
}
return (binary);
}