-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbinary.c
More file actions
49 lines (41 loc) · 691 Bytes
/
Copy pathbinary.c
File metadata and controls
49 lines (41 loc) · 691 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
#include "holberton.h"
/**
* itob - change int to binary
* @list: int to change
* Return: string with binary
*/
char *itob(va_list list)
{
int j = 0, twos = 1;
int i, k;
char *s;
k = va_arg(list, int);
i = k;
/* malloc up to max int in binary */
s = malloc(sizeof(char) * 33);
if (s == NULL)
return (NULL);
/* account for negative numbers with '1' at index 0 */
if (k < 0)
{
s[0] = 1 + '0';
j++;
k *= -1;
i *= -1;
}
/* find biggest power of 2 it's divisible by */
while (k > 1)
{
k /= 2;
twos *= 2;
}
/* divide down and store binary num */
while (twos > 0)
{
s[j++] = (i / twos + '0');
i %= twos;
twos /= 2;
}
s[j] = '\0';
return (s);
}