-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteger.c
More file actions
105 lines (96 loc) · 2.66 KB
/
integer.c
File metadata and controls
105 lines (96 loc) · 2.66 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* integer.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abaur <abaur@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/05 16:32:09 by abaur #+# #+# */
/* Updated: 2020/10/17 15:25:54 by abaur ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int base_size(const char *base)
{
int i;
i = -1;
while (base[++i])
if (ft_strcontain("\t\n\r\v\f +-", base[i])
|| ft_strcontain(&base[i + 1], base[i]))
return (0);
return ((i < 2) ? 0 : i);
}
int ft_atoi_base(const char *str, const char *base)
{
short sign;
int dozen;
int result;
int digit;
if (!(dozen = base_size(base)))
return (0);
while (ft_strcontain("\t\n\r\v\f ", *str))
str++;
sign = 1;
if (*str == '+' || *str == '-')
if (*str++ == '-')
sign *= -1;
result = 0;
while (*str)
{
digit = indexof(*str, base);
if (digit < 0)
return (result);
result *= dozen;
result += digit * sign;
str++;
}
return (result);
}
/*
** This writes an integer into a string recursively.
** The first iteration writes the last number, it finds the pointer to the last
** character by asking th next iteration; The last iteration writes into the
** first character, and returns the next pointer to the previous iteration,
** which only then execute its own logic.
**
** In a way, the very last iteration is executed first.
*/
static char *ft_itoa_write(int nb, const char *base, int dozen, char *output)
{
if (nb <= -dozen || dozen <= nb)
output = ft_itoa_write(nb / dozen, base, dozen, output);
else if (nb < 0)
*(output++) = '-';
nb %= dozen;
if (nb < 0)
nb *= -1;
*output = base[nb];
output++;
*output = '\0';
return (output);
}
char *ft_itoa_base(int nbr, const char *base)
{
size_t len;
int dozen;
long digit;
char *result;
if (!(dozen = base_size(base)))
return (0);
len = 1;
digit = nbr;
if (digit < 0)
{
digit *= -1;
len++;
}
while (digit >= dozen)
{
len++;
digit /= dozen;
}
if (!(result = (char*)malloc(sizeof(char) * (len + 1))))
return (NULL);
ft_itoa_write(nbr, base, dozen, result);
return (result);
}