-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_8_general_number_converter.cpp
95 lines (72 loc) · 1.72 KB
/
2_8_general_number_converter.cpp
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
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <string>
#include <math.h>
using std::cin;
using std::cout;
using std::endl;
using std::pow;
/*
Converting numbers with different bases without using strings or arrays.
*/
void numberConverter(int baseX, int baseY);
int toDecimalConverter(int baseX);
void fromDecimalConverter(int dec, int baseY);
int main()
{
int baseX = 0, baseY = 0;
cout << "Type in the base of the number to convert from:\n";
cin >> baseX;
cin.ignore();
cout << "Type in the base you'll convert to:\n";
cin >> baseY;
cin.ignore();
cout << "Type in the number: \n";
numberConverter(baseX, baseY);
cin.get();
return 0;
}
void numberConverter(int baseX, int baseY)
{
int dec = toDecimalConverter(baseX);
fromDecimalConverter(dec, baseY);
}
int toDecimalConverter(int baseX)
{
int digitSize = 64 / baseX;
char ch = '0';
int dec = 0;
int digit = 0;
int digitCount = 0;
cout << "Before while loop" << endl;
while(ch != 10 && digitCount <= digitSize)
{
ch = cin.get();
if (ch == ' ' || ch == 10) continue;
digit = ch < 'A' ? ch - '0': ch - 'A' + 10;
dec = dec*baseX + digit;
digitCount++;
}
cout << "After while loop" << endl;
return dec;
}
void fromDecimalConverter(int dec, int baseY)
{
int temp = dec;
int c = 0;
int n = -1;
int digit = 0;
char charDigit = 0;
while (temp) {
n++;
temp /= baseY;
}
temp = dec;
cout << "The number is:" << endl;
do {
c = pow(baseY, n--);
digit = (temp / c) % baseY;
charDigit = digit < 10 ? '0' + digit: digit + 'A' - 10;
cout << charDigit;
} while(n >= 0);
cout << "\n";
}