-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_atoi.c
91 lines (82 loc) · 1.85 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lgillot- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/05/07 22:01:23 by lgillot- #+# #+# */
/* Updated: 2015/11/24 11:57:33 by lgillot- ### ########.fr */
/* */
/* ************************************************************************** */
#include <limits.h>
#include "libft.h"
static void skip_spaces(const char **str)
{
while (ft_isspace(**str))
{
(*str)++;
}
}
static int parse_sign(const char **str)
{
if (**str == '+')
{
(*str)++;
return (1);
}
else if (**str == '-')
{
(*str)++;
return (-1);
}
return (1);
}
static int parse_digit(const char **str)
{
int digit;
if (ft_isdigit(**str))
{
digit = (int)**str - 48;
(*str)++;
return (digit);
}
else
{
return (-1);
}
}
static int overflow(int sign, int old, int new)
{
if (sign > 0)
{
return (new < old);
}
else
{
return (new > old);
}
}
int ft_atoi(const char *str)
{
int sign;
int digit;
int old_result;
int result;
skip_spaces(&str);
sign = parse_sign(&str);
result = 0;
digit = 0;
while (digit >= 0)
{
old_result = result;
result *= 10;
result += digit * sign;
if (overflow(sign, old_result, result))
{
return (sign > 0 ? (int)LONG_MAX : (int)LONG_MIN);
}
digit = parse_digit(&str);
}
return (result);
}