-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_atoi.c
73 lines (67 loc) · 1.98 KB
/
ft_atoi.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bhagenlo <[email protected]. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/28 19:03:13 by bhagenlo #+# #+# */
/* Updated: 2022/10/26 15:23:42 by bhagenlo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_skipwhite(const char *str, long long int *i, int *isneg)
{
if (str == NULL || i == NULL)
return ;
while ((str[*i] == ' ' || str[*i] == '\t' || str[*i] == '\n')
|| (str[*i] == '\r' || str[*i] == '\v' || str[*i] == '\f'))
(*i)++;
if (str[*i] != '\0' && str[*i] == '-')
{
*isneg = 1;
(*i)++;
}
else if (str[*i] == '+')
(*i)++;
}
int ft_atoi(const char *a)
{
long long i;
long long nbr;
int isneg;
long long long_max;
i = 0;
nbr = 0;
isneg = 0;
long_max = 922337203685477580;
ft_skipwhite(a, &i, &isneg);
while (a[i] != '\0' && ft_isdigit(a[i]))
{
if (nbr > long_max || (nbr == long_max && a[i] > '7'))
return (!isneg * -1);
nbr = (nbr * 10) + (a[i++] - '0');
}
if (isneg)
nbr = -nbr;
return (nbr);
}
bool ft_parse_int(const char *s, int *loc)
{
int i;
long long num;
int neg;
num = 0;
i = 0;
neg = (s[i] == '-');
i += neg;
while (s[i] != '\0' && ft_isdigit(s[i]))
{
num = (num * 10) + (s[i] - '0');
if (num > (((long long)INT_MAX) + neg))
return (false);
i++;
}
*loc = (int)(num * -((2 * neg) - 1));
return (i > neg && s[i] == '\0');
}