-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_atoi.c
More file actions
69 lines (62 loc) · 1.94 KB
/
Copy pathft_atoi.c
File metadata and controls
69 lines (62 loc) · 1.94 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssoeno <ssoeno@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/17 17:25:49 by ssoeno #+# #+# */
/* Updated: 2024/04/28 19:48:45 by ssoeno ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static long handle_overflow(const char *str, int sign)
{
unsigned long ret;
int digit;
unsigned long cutoff;
ret = 0;
cutoff = (unsigned long)LONG_MAX;
while (ft_isdigit(*str))
{
digit = *str - '0';
if (sign == 1 && ret > ((cutoff - digit) / 10))
return (LONG_MAX);
if (sign == -1 && ret > ((cutoff + 1 - digit) / 10))
return (LONG_MIN);
ret = ret * 10 + digit;
str++;
}
return (ret);
}
static int is_space(const char c)
{
return ((c >= 9 && c <= 13) || c == 32);
}
int ft_atoi(const char *str)
{
long result;
int sign;
result = 0;
sign = 1;
while (is_space(*str))
str++;
if (*str == '-' || *str == '+')
{
if (*str == '-')
sign = -1;
str++;
}
result = (int)handle_overflow(str, sign);
return ((sign * result));
}
// int main()
// {
// int original = atoi("9223372036854775808");
// int ft = ft_atoi("9223372036854775808");
// printf("%d\n", original);
// printf("%d\n", ft);
// }
// // int original = atoi("18446744073709551620");
// // int ft = ft_atoi("18446744073709551620");
// ft_atoi("9223372036854775808"));