This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa_base.c
executable file
·72 lines (66 loc) · 1.94 KB
/
ft_itoa_base.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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_itoa_base.c :+: :+: */
/* +:+ */
/* By: fbes <[email protected]> +#+ */
/* +#+ */
/* Created: 2021/03/11 00:08:06 by fbes #+# #+# */
/* Updated: 2022/02/08 19:48:05 by fbes ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static int is_valid_base(char *base)
{
int i;
int j;
i = 0;
while (base[i] != '\0')
{
if (base[i] == '+' || base[i] == '-')
return (0);
j = i + 1;
while (base[j] != '\0')
{
if (base[i] == base[j])
return (0);
j++;
}
i++;
}
if (i < 2)
return (0);
return (1);
}
static void nbr_loop(char *ret, unsigned int n, char *base, int base_num)
{
if (n != 0)
{
nbr_loop(ret - 1, n / base_num, base, base_num);
*ret = base[n % base_num];
}
}
/**
* Convert a number in any base into a string
* @param[in] n The number to convert
* @param[in] *base The base to use (ex.: "0123456789ABCDEF")
* @return The converted number in string format, NULL on error
*/
char *ft_itoa_base(unsigned int n, char *base)
{
int base_num;
char *ret;
int num_len;
base_num = ft_strlen(base);
if (!is_valid_base(base))
return (0);
num_len = ft_numlen(n, base_num);
ret = ft_calloc(num_len + 1, sizeof(char));
if (!ret)
return (NULL);
if (n == 0)
ret[0] = base[0];
else
nbr_loop(ret + num_len - 1, n, base, base_num);
return (ret);
}