Line | Branch | Exec | Source |
---|---|---|---|
1 | /* | ||
2 | ** EPITECH PROJECT, 2023 | ||
3 | ** my_convert_base | ||
4 | ** File description: | ||
5 | ** Returns the result of the conversion of a number (nbr) | ||
6 | ** in a specific base (base_from) to another base (base_to) | ||
7 | */ | ||
8 | /** | ||
9 | * @file my_convert_base.c | ||
10 | * @brief The file containing the my_convert_base function | ||
11 | * @author Nicolas TORO | ||
12 | */ | ||
13 | |||
14 | #include "my.h" | ||
15 | |||
16 | 26 | static char *put_str_nb(int nb, char const *base, int base_len, int negative) | |
17 | { | ||
18 | 26 | int len_nb = 1; | |
19 | 26 | int temp_nb = nb; | |
20 | char *nb_str; | ||
21 | 26 | int figure_temp = nb; | |
22 | |||
23 |
2/2✓ Branch 0 taken 76 times.
✓ Branch 1 taken 26 times.
|
102 | while ((temp_nb / base_len) != 0) { |
24 | 76 | len_nb = len_nb + 1; | |
25 | 76 | temp_nb = temp_nb / base_len; | |
26 | } | ||
27 | 26 | nb_str = malloc(sizeof(char) * (len_nb + negative)); | |
28 |
2/2✓ Branch 0 taken 1 times.
✓ Branch 1 taken 25 times.
|
26 | if (negative == 1) |
29 | 1 | nb_str[0] = '-'; | |
30 |
2/2✓ Branch 0 taken 102 times.
✓ Branch 1 taken 26 times.
|
128 | for (int i = 0; i < len_nb; i++) { |
31 | 102 | nb_str[len_nb - i - 1 + negative] = base[figure_temp % base_len]; | |
32 | 102 | figure_temp = (figure_temp - (figure_temp % base_len)) / base_len; | |
33 | } | ||
34 | 26 | nb_str[len_nb] = '\0'; | |
35 | 26 | return my_strdup(nb_str); | |
36 | } | ||
37 | |||
38 | 26 | static char *my_setnbr_base(int nbr, char const *base) | |
39 | { | ||
40 | 26 | int negative = 0; | |
41 | 26 | int base_len = 0; | |
42 | |||
43 |
2/2✓ Branch 0 taken 1 times.
✓ Branch 1 taken 25 times.
|
26 | if (nbr < 0) { |
44 | 1 | negative = 1; | |
45 | 1 | nbr = -nbr; | |
46 | } | ||
47 |
2/2✓ Branch 0 taken 252 times.
✓ Branch 1 taken 26 times.
|
278 | while (base[base_len] != '\0') |
48 | 252 | base_len = base_len + 1; | |
49 | 26 | return put_str_nb(nbr, base, base_len, negative); | |
50 | } | ||
51 | |||
52 | 26 | char *my_convert_base(char const *nbr, | |
53 | char const *base_from, char const *base_to) | ||
54 | { | ||
55 | 26 | int number = my_getnbr_base(nbr, base_from); | |
56 | 26 | char *result = my_setnbr_base(number, base_to); | |
57 | |||
58 | 26 | return result; | |
59 | } | ||
60 |