-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_iutoa_base_bonus.c
92 lines (82 loc) · 2.14 KB
/
ft_iutoa_base_bonus.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_iutoa_base_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edi-marc <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 10:29:06 by edi-marc #+# #+# */
/* Updated: 2021/08/05 15:51:11 by edi-marc ### ########.fr */
/* */
/* ************************************************************************** */
/*
** LIBRARY: libft
** SYNOPSIS: convert an unsigned int to a string in any base
**
** DESCRIPTION:
** The iutoa_base() function converts an unsigned int to a string in a base
** specified by the string base.
** Returns the number represented as ASCII string,
** NULL otherwise.
**
** The base 1 case, unary numeral system, is treated as a unique case
*/
#include "libft.h"
static char *ft_iutoa_unary(unsigned int n, char *base)
{
char *p;
p = ft_calloc(n + 1, sizeof(*p));
if (p)
{
while (n)
p[--n] = *base;
}
return (p);
}
static size_t count_digits_b(unsigned int n, size_t len_b)
{
size_t num;
num = 0;
if (!n)
num = 1;
while (n)
{
n = n / len_b;
num++;
}
return (num);
}
static void convert(unsigned int n, char *p, size_t digits, char *base)
{
size_t len_b;
len_b = ft_strlen(base);
if (!n)
*p = base[n];
while (n)
{
p[digits - 1] = base[n % len_b];
n = n / len_b;
digits--;
}
}
char *ft_iutoa_base(unsigned int n, char *base)
{
char *p;
size_t digits;
size_t len_b;
p = NULL;
if (base && *base)
{
len_b = ft_strlen(base);
if (len_b > 1)
{
digits = count_digits_b(n, len_b);
p = ft_calloc(digits + 1, sizeof(*p));
if (p)
convert(n, p, digits, base);
}
else
p = ft_iutoa_unary(n, base);
}
return (p);
}