-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprint_binary.c
More file actions
42 lines (38 loc) · 739 Bytes
/
print_binary.c
File metadata and controls
42 lines (38 loc) · 739 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
#include "main.h"
/**
* print_binary - Converts a number from base 10 to binary
* @list: List of arguments passed to this function
* Return: The length of the number printed
*/
int print_binary(va_list list)
{
unsigned int num;
int i, len;
char *str;
char *rev_str;
num = va_arg(list, unsigned int);
if (num == 0)
return (_putchar('0'));
if (num < 1)
return (-1);
len = base_len(num, 2);
str = malloc(sizeof(char) * len + 1);
if (str == NULL)
return (-1);
for (i = 0; num > 0; i++)
{
if (num % 2 == 0)
str[i] = '0';
else
str[i] = '1';
num = num / 2;
}
str[i] = '\0';
rev_str = rev_string(str);
if (rev_str == NULL)
return (-1);
write_base(rev_str);
free(str);
free(rev_str);
return (len);
}