forked from jbarbier/printf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumbershelper.c
More file actions
80 lines (70 loc) · 1.31 KB
/
numbershelper.c
File metadata and controls
80 lines (70 loc) · 1.31 KB
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
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/*functions to convert a number in decimal to a different base
*necessitates use of malloc to reverse the string the result are stored in
*/
/**
* _nlen - size of a number
* @n: a number
* Return: the number of digits in this number
*/
int _nlen(unsigned int n)
{
int i;
i = 0;
do {
++i;
n /= 10;
} while (n > 0);
return (i);
}
/**
* reverse_array - reverse an array of characters
* @a: array;
* @n: number of elements in array
*/
void reverse_array(char *a, int n)
{
int i;
int temp;
i = 0;
n = n - 1;
while (i < n)
{
temp = a[i];
a[i] = a[n];
a[n] = temp;
i++;
n--;
}
}
/**
* base_conv - converts a positive integer in decimal to another base
* @n: positive number or 0
* @base: base to convert number to
* @choice: the ascii characters needed
* Return: a string containing the values
*/
char *base_conv(unsigned int n, int base, char *choice)
{
int l, i, init_l;
char *result;
l = _nlen(n);
init_l = 0;
if (base >= 10)
init_l = l + 1;
else if (base >= 8)
init_l = (l + 1) + 1;
else
init_l = 8 * sizeof(unsigned int) + 1;
result = malloc(init_l * sizeof(char));
i = 0;
do {
result[i++] = choice[n % base];
n = n / base;
} while (n > 0);
reverse_array(result, i);
result[i] = '\0';
return (result);
}