-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitoa.c
102 lines (90 loc) · 1.38 KB
/
itoa.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdlib.h>
#include "main.h"
/**
* Itoa - changes from integer to string
* @n: the number
* Return: a string of the number
*/
char *Itoa(int n);
char *Itoa(int n)
{
unsigned int n1;
char *buffer;
int i, length = 0;
unsigned int temp;
if (n == 0)
{
buffer = malloc(2 * sizeof(char));
if (buffer == NULL)
return (NULL);
buffer[0] = '0';
buffer[1] = '\0';
return (buffer);
}
if (n < 0)
{
length++;
n1 = (unsigned int)(-n);
}
else
{
n1 = (unsigned int)n;
}
temp = n1;
while (temp > 0)
{
length++;
temp /= 10;
}
buffer = malloc((length + 1) * sizeof(char));
if (buffer == NULL)
{
return (NULL);
}
buffer[length] = '\0';
for (i = length - 1; i >= 0; i--)
{
buffer[i] = (n1 % 10) + '0';
n1 /= 10;
}
if (n < 0)
{
buffer[0] = '-';
}
return (buffer);
}
/**
* bin_convert - prints binary equivalent of a decimal number
* @n: number to print in binary
* Return: a string of binary characters
*/
char *bin_convert(unsigned long int n)
{
int i, count = 0;
unsigned long int current;
char *string;
string = malloc(64 + 1);
if (string == NULL)
return (NULL);
for (i = 63; i >= 0; i--)
{
current = n >> i;
if (current & 1)
{
string[count] = '1';
count++;
}
else if (count)
{
string[count] = '0';
count++;
}
}
if (!count)
{
string[count] = '0';
count++;
}
string[count] = '\0';
return (string);
}