Click to See Complete Forum and Search --> : Look here for an amusing number base conversion program


torus13
December 28th, 2006, 08:02 PM
Here is source code for an amusing little program I wrote that will take a list of numbers from a text file and convert each of them to a range of bases from 1 to 206. Symbols for bases above 10 are taken from the ascii table (so I guess it works for bases from 1 to 207, but a space symbol in a number string isn't terribly useful):


#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;
typedef unsigned short ushort;
void convert(ushort number, ushort const base, ofstream & outfile);

int main()
{
ifstream input;
input.open("c:\\conversion_input.txt", ios::in);

if (!input)
{
cout << "Input file can't be opened." << endl;
system("PAUSE");
return 0;
}

ofstream results;
results.open("c:\\conversion_output.txt", ios::out);

if (!results)
{
cout << "Output file can't be opened." << endl;
system("PAUSE");
return 0;
}

ushort basei;
ushort basej;
cout << endl << "Enter the base to start with: ";
cin >> basei;
cout << endl << "Enter the base to end with: ";
cin >> basej;

ushort num;

while(!input.eof())
{
input >> num;
results << "(" << num << ")" << endl;

for (int j=basei; j<=basej; j++)
{
results << j << ":" << "\t";
convert(num,j, results);
results << endl;
}

results << endl;
}

input.close();
results.close();
return 0;
}

void convert(ushort num, ushort const base, ofstream & outfile)
{

if (base == 1)
{

for (int i=0; i<num; i++)
outfile << 1;

return;
}

if (num < base)
{
outfile << char(num+48);
return;
}

convert(num/base, base, outfile);
outfile << char(num%base+48);
return;
}


You need this input file: c:\conversion_output.txt (I'm a beginner about file input/output so this program won't ask for the input file's directory).
In conversion_output.txt, make sure to arrange your input exactly like so:

1
2
3
4
5
6
...and so on.

This site will generate prime numbers arranged in the correct format: http://www.rsok.com/~jrm/printprimes.html
Just copy and paste directly into c:\conversion_input.txt.

The program will ask for a range of bases. The result will be printed in c:\conversion_output.txt.

Enjoy! (or don't. I wrote this in one evening so its not sophisticated in the LEAST).

A word of warning: this program is very breakable (like I said, wrote in one evening). I don't have any exception handling or anything. For example, putting in negative or real number bases will break it!

Tell me what you think of this little program! I'd also appreciate critique of my code, if you like.