summaryrefslogtreecommitdiff
path: root/c/dataStructure/baseConversion.c
blob: 8f7bd461db66d582e49bcbfc535b294bb208218f (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
// default base is decimal to binary
// run program with flag to start with different base

#include<stdio.h>
#include<stdlib.h>

typedef struct stack {
    int * base;
    int top;
    int size;
} Stack;

void getSpace(Stack * s)
{
    if (s->size == 0)
    {
        s->size = 1;
        s->base = (int *) calloc (s->size,sizeof(int));
    }
    else
    {
        s->size += 1;
        s->base = (int *) realloc (s->base, sizeof(int) * s->size);
    }
}

void conversion(Stack * s, int from, int to)
{
    while (from != 0)
    {
        if (s->size <= s->top)
            getSpace(s);
        s->base[s->top++] = from % to;
        from /= to;
    }
}

void print(Stack * s, int from)
{
    printf("origin\t\tbinary\n");
    printf("%d\t\t",from);
    while (s->top != 0)
        printf("%d",s->base[--s->top]);
    s->top = 0;
    putchar('\n');
}

int getNumber(void)
{
    int tmp;

    if (scanf("%d", &tmp) != 1)
        exit(EXIT_SUCCESS);
    return tmp;
}

int main(void)
{
    Stack storage = {NULL, 0, 0};

    int from = getNumber();
    int to = 2;

    conversion(&storage,from,to);

    print(&storage,from);

    free(storage.base);

    return 0;
}