-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_atoi_base.c
115 lines (100 loc) · 2.61 KB
/
ft_atoi_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
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
106
107
108
109
110
111
112
113
114
115
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anpayot <anpayot@student.42lausanne.ch> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/17 17:27:43 by anpayot #+# #+# */
/* Updated: 2024/10/27 17:16:30 by anpayot ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_get_sign(const char **str)
{
int sign;
sign = 1;
while (ft_isspace(**str))
(*str)++;
if (**str == '-')
{
sign = -1;
(*str)++;
}
else if (**str == '+')
(*str)++;
return (sign);
}
static long ft_handle_overflow(long result, int base_len, int digit, int sign)
{
long max_int;
long min_int;
max_int = (long)INT_MAX;
min_int = (long)INT_MIN;
if (result > max_int / base_len
|| (result == max_int / base_len && digit > max_int % base_len))
{
if (sign == 1)
{
return (max_int);
}
else
{
return (min_int);
}
}
return (result);
}
int ft_atoi_base(const char *str, const char *base)
{
int base_len;
long result;
int sign;
int digit;
const char *base_ptr;
if (!ft_isvalid_base(base, &base_len))
return (0);
sign = ft_get_sign(&str);
result = 0;
while (*str)
{
base_ptr = ft_strchr(base, *str);
if (!base_ptr)
break ;
digit = base_ptr - base;
result = ft_handle_overflow(result, base_len, digit, sign);
result = result * base_len + digit;
str++;
}
return ((int)(result * sign));
}
/*
#include <stdio.h>
int main(void)
{
const char *str = "42";
const char *base = "0123456789";
int result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
str = "-42";
result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
base = "01";
str = "101010";
result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
base = "0123456789ABCDEF";
str = "2A";
result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
base = "0123456789abcdef";
str = "2a";
result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
base = "01234567";
str = "52";
result = ft_atoi_base(str, base);
printf("Result: %d\n", result);
return 0;
}
*/