954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Base Conversion Program

IT currently is set up for base 3, but should be able to make a couple of minor changes and convert to any base, thanks and hope it helps someone out.

#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

void convert_base(int v, int b);
ifstream inputdata;
ofstream outputdata;

int main(int argc, char *argv[]){
    //int a, b, c, d, e, f, i;
    int v;
    int base = 3;

    inputdata.open("Base_Conversion_File.dat");
    if(!inputdata){
        cout << "There was a problem opening the data file." << endl;
        return 1;
    }
    inputdata >> v;
    outputdata.open("Converted_data.out");
    if(!outputdata){
        cout << "There was a problem created the output file." << endl;
    }
  while (inputdata >> v) {
    outputdata << v << " converted to base " << base << " is ";
    convert_base( v, base );
    outputdata << "\n";
  }
    inputdata.close();
    outputdata.close();
    return 0;
}

void convert_base(int v, int b){
    int k, i;
    int max;

    k = floor(log10(v)/log10(b)) + 1;
    max = k;

    for(i = 0; i < max; i++){
    outputdata << (int)(v/ pow(b, k-1));

        v = v % (int)pow(b, k-1);
        k = k - 1;

    }
    outputdata << endl;
}
monkeybut
Newbie Poster
11 posts since Sep 2011
Reputation Points: 11
Solved Threads: 0
 

May I humbly suggest that you avoid the need to use transcendental functions (log and pow) and those nasty C-style casts by doing this:

void convert_base(int v, int b){
    std::stringstream ss;
    
    do { ss << (v % b); } while( v /= b );

    std::string s = ss.str();
    std::copy( s.rbegin(), s.rend(), ostream_iterator<char>(outputdata) );
    outputdata << std::endl;
}
mike_2000_17
Posting Virtuoso
Moderator
2,139 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: