-
Notifications
You must be signed in to change notification settings - Fork 103
/
ft_atoi_base.c
51 lines (43 loc) · 835 Bytes
/
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
#include <stdio.h>
char to_lower(char c)
{
if (c >= 'A' && c <= 'Z')
return (c + ('a' - 'A'));
return (c);
}
int get_digit(char c, int digits_in_base)
{
int max_digit;
if (digits_in_base <= 10)
max_digit = digits_in_base - 1 + '0';
else
max_digit = digits_in_base - 10 - 1 + 'a';
if (c >= '0' && c <= '9' && c <= max_digit)
return (c - '0');
else if (c >= 'a' && c <= 'f' && c <= max_digit)
return (10 + c - 'a');
else
return (-1);
}
int ft_atoi_base(const char *str, int str_base)
{
int result = 0;
int sign = 1;
int digit;
if (str == NULL || str_base < 2 || str_base > 16)
return 0;
if (*str == '-')
{
sign = -1;
++str;
}
while (*str)
{
digit = get_digit(to_lower(*str), str_base);
if (digit == -1)
break;
result = result * str_base + digit;
++str;
}
return (result * sign);
}