Jan 20, 2012 (last update: Jan 21, 2012)
Decimal to radix conversion
Score: 2.6/5 (20 votes)
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <iostream>
#include <limits>
#include <string>
// Positional value
unsigned short store = 0;
// This is to hold how many positions we need to check
unsigned short highest;
unsigned short base;
unsigned long number;
bool first;
// Return a number input
int cin_int(std::string msg);
int main() {
std::cout << "Decimal to Radix converter\n\
Instead of representing values that are above 9 as letters (e.g., in hex) a value is shown in between pipes.\
(Converting 255 to hex would not output 'FF', it would output '15|15')\n(Ctrl+C
to exit)\n";
while (true) {
highest = 1;
base = cin_int("Enter an integer radix:\n");
number = cin_int("Enter an integer to convert:\n");
std::cout << "Result of conversion: \n";
// Figure out the highest position that the number could calculate to
for (unsigned short i = 1; i < number; i *= base) {
highest *= base;
}
first = true;
for (unsigned short i = highest; i > 0; i /= base) {
// Prevent a leading 0
if (first) {
first = false;
continue;
}
store = 0;
for (unsigned short d = 1; d < base; d++) {
if (number / i % base == d) {
store = d;
}
}
std::cout << store;
// Output a pipe between positions
if (i >= base) {
std::cout << '|';
}
}
std::cout << std::endl;
}
return 0;
}
int cin_int(std::string msg) {
int num;
while (true) {
std::cout << msg;
while (!(std::cin >> num)) {
std::cout << msg;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
if (num > 1) break;
else {
std::cout << "Input must be above 1!\n";
}
}
return num;
}
| |