summaryrefslogtreecommitdiff
path: root/graphs/piscine/my_itoa_base/my_itoa_base.c
blob: 29b304294b987ad0ba6c3d3d061680bc69d946c2 (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
#include "my_itoa_base.h"

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

char *my_itoa_base(int n, char *s, const char *base)
{
    if (n == 0)
    {
        s[0] = base[0];
        s[1] = '\0';
        return s;
    }
    char *head = s;
    if (n < 0)
    {
        s[0] = '-';
        s++;
        n = -n;
    }

    // count numbers
    int t = n;
    int m = 0;
    int b = base_count(base);
    while (t > 0)
    {
        t /= b;
        m++;
    }

    // n = number count
    s[m] = '\0';
    m--;
    for (; m >= 0; m--)
    {
        s[m] = base[n % b];
        n /= b;
    }

    return head;
}