-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnumber_to_string.c
More file actions
executable file
·78 lines (73 loc) · 1.65 KB
/
number_to_string.c
File metadata and controls
executable file
·78 lines (73 loc) · 1.65 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
#include "shell.h"
/**
* reverse_str - reverse string
* @str: string to reverse
* @size: size of string
* @keep_first: Keep first element in str like first
*/
void reverse_str(char *str, int size, char keep_first)
{
int length, iterator;
char aux;
if (keep_first)
reverse_str(str + 1, size - 1, 0);
else
{
length = size % 2 == 0 ? size / 2 : ((size / 2) + 1);
for (iterator = 0; iterator < length; iterator++)
{
aux = str[iterator];
str[iterator] = str[size - iterator - 1];
str[size - iterator - 1] = aux;
}
}
}
/**
* number_to_string - convert number to string
* you should free the pointer returned
* @number: number to be printed
* @base: base to be converted if want in hexa wit capital letters
* Return: string converted
*/
char *number_to_string(int number, char base)
{
int lengh = 0, aux;
char sign, numbers[] = "0123456789abcdef", *p = malloc(1);
sign = number < 0;
if (p == NULL || base > 17)
return (NULL);
do {
if (number < 0)
{
p[0] = base == 2 ? '1' : '-';
lengh++;
p = _realloc(p, lengh, lengh + 1);
aux = base == 17 ? number % (base - 1) : number % base;
p[lengh] = numbers[-aux];
if (base == 17 && -aux > 9)
p[lengh] = p[lengh] - 'a' + 'A';
aux = base == 17 ? number / (base - 1) : number / base;
number = -aux;
}
else
{
if (base == 17)
{
p[lengh] = numbers[number % (base - 1)] - 'a' + 'A';
number /= (base - 1);
}
else
{
p[lengh] = numbers[number % base];
number /= base;
}
}
lengh++;
p = _realloc(p, lengh, lengh + 1);
if (p == NULL)
return (NULL);
p[lengh] = '\0';
} while (number);
reverse_str(p, lengh, sign);
return (p);
}