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