-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary.c
More file actions
52 lines (48 loc) · 817 Bytes
/
binary.c
File metadata and controls
52 lines (48 loc) · 817 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
46
47
48
49
50
51
52
#include "main.h"
/**
* conv_binary - conv numbers to binary string
* @num: number
* Return: binary num as string
*/
char *conv_binary(unsigned int num)
{
int i = 0, j = 0;
char *bstr, rev_bstr[32];
if (num == 0)
{
bstr = malloc(sizeof(char) * 2);
if (bstr == NULL)
return (NULL);
bstr[0] = 0 + '0';
bstr[1] = '\0';
}
else
{
while (num != 0)
{
rev_bstr[i] = (num % 2) + '0';
num /= 2;
i++;
}
bstr = malloc(sizeof(char) * (i + 1));
if (bstr == NULL)
return (NULL);
for (j = 0; j < i; j++)
{
bstr[j] = rev_bstr[i - 1 - j];
}
bstr[j] = '\0';
}
return (bstr);
}
/**
* print_binary - printf the binary string
* @num: number
* Return: num of chars printed
*/
int print_binary(unsigned int num)
{
char *s2;
s2 = conv_binary(num);
return (print_str(s2));
}