Monday, 18 March 2013

C Programming - convert number to any base

Just to continue with my programming practice I decided to write a function which takes a number and a base and converts that number to that base.

Here's the function:

//takes a number and a base to work to. It converts (just prints) this number to said base
//base has to be greater then 1
void printInBase(int number, int base) {
    
    assert(base > 1);
    
//find out how many units is needed to make the number
//int numberOfUnits = 1;
int units = base;
while (units <= number) {
//numberOfUnits ++;
units = units * base;
}
    //make an array which will be printed out in the end
    //int numberArray [numberOfUnits];
//work out which how many of each unit
    //int i = 0;
    
int result = number;
while (units > 1) {
units = units / base;
printf("%d", result / units);
result = result % units;
        //i++;
}
 
//prints out array
    //for (int c = 0; c <= numberOfUnits ; c++) {
    //    printf("%d", numberArray[c]);
    //}
}
 Output:
Type a starting number: 1
Type an end number: 30
Type a base to count in: 7
1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
6 = 6
7 = 10
8 = 11
9 = 12
10 = 13
11 = 14
12 = 15
13 = 16
14 = 20
15 = 21
16 = 22
17 = 23
18 = 24
19 = 25
20 = 26
21 = 30
22 = 31
23 = 32
24 = 33
25 = 34
26 = 35
27 = 36
28 = 40
29 = 41
30 = 42
The function fails at counting base 1, but it hurts my brain too much to think about it! Also, to count in a base larger then 10, it's best to put a comma between digits. e.g:

Type a starting number: 1
Type an end number: 30
Type a base to count in: 15
1 = 1,
2 = 2,
3 = 3,
4 = 4,
5 = 5,
6 = 6,
7 = 7,
8 = 8,
9 = 9,
10 = 10,
11 = 11,
12 = 12,
13 = 13,
14 = 14,
15 = 1,0,
16 = 1,1,
17 = 1,2,
18 = 1,3,
19 = 1,4,
20 = 1,5,
21 = 1,6,
22 = 1,7,
23 = 1,8,
24 = 1,9,
25 = 1,10,
26 = 1,11,
27 = 1,12,
28 = 1,13,
29 = 1,14,
30 = 2,0,
This way you can distinguish between the 10's and 20's etc. Might be worth putting this in the function. But also, I could make it convert to hexadecimal? Might require more brain hurt.

No comments:

Post a Comment