summaryrefslogtreecommitdiff
path: root/graphs/piscine/my_atoi_base/my_atoi_base.c
blob: 46b45606205c4731c23370acf11dcd14aad49317 (plain)
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
#include "my_atoi_base.h"

int val_in_base(char c, const char *base)
{
    size_t i;
    for (i = 0; base[i] && base[i] != c; i++)
    {
        continue;
    }

    if (base[i])
    {
        return i;
    }

    return -1;
}

int base_size(const char *base)
{
    int res;
    for (res = 0; base[res]; res++)
    {
        continue;
    }
    return res;
}

int my_atoi_base(const char *str, const char *base)
{
    int res = 0;

    // str error check
    if (str == NULL || *str == '0')
    {
        return 0;
    }

    // trim whitespaces
    for (; *str && *str == ' '; str++)
    {
        continue;
    }

    // move to end of str
    size_t l;
    for (l = 0; str[l]; l++)
    {
        continue;
    }
    l--;

    // prepare for calculations
    int b = base_size(base);
    int factor = 1;

    // actual conversion of up to the second element of str (potential sign)
    for (; l > 0; l--)
    {
        int val = val_in_base(str[l], base);
        if (val == -1)
        {
            return 0;
        }
        res += val * factor;

        factor *= b;
    }

    // l should be 0 by now
    if (str[l] == '-')
    {
        return -res;
    }
    else if (str[l] != '+')
    {
        int val = val_in_base(str[l], base);
        if (val == -1)
        {
            return 0;
        }
        return res + val * factor;
    }

    return res;
}