Start New Discussion within our Software Development Community

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;"Base_Conversion_File.dat");
        cout << "There was a problem opening the data file." << endl;
        return 1;
    inputdata >> v;"Converted_data.out");
        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";
    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;

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;
This question has already been answered. Start a new discussion instead.