-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions_numbers.c
154 lines (139 loc) · 2.28 KB
/
functions_numbers.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include "holberton.h"
/**
* save_number - save a number
* @args: List of arguments
* @dest: Destiny to copy
* @pos: Position of destiny
* Return: The length
*/
int save_number(va_list args, char *dest, int *pos)
{
int n, div, len;
unsigned int num;
n = va_arg(args, int);
div = 1;
len = 0;
if (n < 0)
{
len++;
copyto_buffer(dest, '-', pos);
num = n * -1;
}
else
num = n;
for (; num / div > 9; )
div *= 10;
for (; div != 0; )
{
len++;
copyto_buffer(dest, ('0' + num / div), pos);
num %= div;
div /= 10;
}
return (len);
}
/**
* _base - length for an octal number
* @num: number
* @base: Base
* Return: Integer
*/
unsigned int _base(unsigned int num, int base)
{
unsigned int i;
for (i = 0; num > 0; i++)
{
num = num / base;
}
return (i);
}
/**
* rev_string - prints a string in reverse
* @s: This is the string to evalu
* not return
*/
void rev_string(char *s)
{
int i = 0;
char word;
int si = 0;
while (s[i] != '\0')
i++;
i -= 1;
while (i > si)
{
word = s[i];
s[i] = s[si];
s[si] = word;
si++;
i--;
}
}
/**
* save_binary - number from base 10 to binary
* @args: arguments
* @dest: destiny to copy
* @pos: actual position in destiny
* Return: number
*/
int save_binary(va_list args, char *dest, int *pos)
{
unsigned int num;
int i, len;
char *str;
num = va_arg(args, unsigned int);
if (num == 0)
{
copyto_buffer(dest, '0', pos);
return (1);
}
len = _base(num, 2);
str = malloc(len + 1);
if (str == NULL)
str = "(null)";
for (i = 0; num > 0; i++)
{
if (num % 2 == 0)
str[i] = '0';
else
str[i] = '1';
num = num / 2;
}
str[i] = '\0';
i = 0;
rev_string(str);
while (str[i] != '\0')
{
copyto_buffer(dest, str[i], pos);
i++;
}
return (i);
}
/**
* save_unsigned - save an unsigned number
* @args: list or arguments
* @dest: Destiny to copy
* @pos: Actual position of number
* Return: Actual position of destiny
*/
int save_unsigned(va_list args, char *dest, int *pos)
{
unsigned int len = 0;
int div = 1;
unsigned int number = va_arg(args, unsigned int);
if (number == 0)
{
copyto_buffer(dest, '0', pos);
return (1);
}
for (; number / div > 9; )
div *= 10;
for (; div != 0; )
{
len++;
copyto_buffer(dest, ('0' + number / div), pos);
number %= div;
div /= 10;
}
return (len);
}