Thursday, 28 March 2013

C Programming - converting a number to hexidecimal and other bases larger then 10

I'm in the middle of writing a program which converts normal base 10 numbers into any base. When you convert to a base larger then 10 it gets a little confusing how to represent those numbers larger than 10. In hexidecimal the numbers 10 through to 15 are represented as A through to F. Here's a function I have written which converts a number in this way, representing larger then 10 numbers into letters up to Z.


//prints a number in a base using symbols for numbers greater than 10
//similar to hexidecimal. Max base is 36
void printInBaseWithUniqueSymbols (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 contains symbols to use from 1 to base
//using a to z for numbers 10 to 36
    char numberArray [base];
for (int i=0; i
if (i<10) {
numberArray[i]=(48+i);
else {
numberArray[i]= (65 + (i-10));
}

}
//printf("%c", numberArray[1]);
//work out which how many of each unit
    //int i = 0;
    
int result = number;
while (units > 1) {
units = units / base;
int numberOfUnits = result / units;
//printf("%c", numberOfUnits);
char character = numberArray[numberOfUnits];
printf("%c", character);
result = result % units;
        //i++;
}

}

Results:

Type a starting number: Running…
1
Type an end number: 100
Type a base to count in: 16
1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
6 = 6
7 = 7
8 = 8
9 = 9
10 = A
11 = B
12 = C
13 = D
14 = E
15 = F
16 = 10
17 = 11
18 = 12
19 = 13
20 = 14
21 = 15
22 = 16
23 = 17
24 = 18
25 = 19
26 = 1A
27 = 1B
28 = 1C
29 = 1D
30 = 1E
31 = 1F
32 = 20
33 = 21
34 = 22
35 = 23
36 = 24
37 = 25
38 = 26
39 = 27
40 = 28
41 = 29
42 = 2A
43 = 2B
44 = 2C
45 = 2D
46 = 2E
47 = 2F
48 = 30
49 = 31
50 = 32
51 = 33
52 = 34
53 = 35
54 = 36
55 = 37
56 = 38
57 = 39
58 = 3A
59 = 3B
60 = 3C
61 = 3D
62 = 3E
63 = 3F
64 = 40
65 = 41
66 = 42
67 = 43
68 = 44
69 = 45
70 = 46
71 = 47
72 = 48
73 = 49
74 = 4A
75 = 4B
76 = 4C
77 = 4D
78 = 4E
79 = 4F
80 = 50
81 = 51
82 = 52
83 = 53
84 = 54
85 = 55
86 = 56
87 = 57
88 = 58
89 = 59
90 = 5A
91 = 5B
92 = 5C
93 = 5D
94 = 5E
95 = 5F
96 = 60
97 = 61
98 = 62
99 = 63
100 = 64

No comments:

Post a Comment