About Me

My photo
Mostly software programming related blogs.

Friday, May 1, 2015

Convert integer from one base to another

Given an integer from any base 2 to 16, convert it into another base 2 to 16. So Binary can be converted to hex, hex to octal or decimal to hex or hex to base 3, hexadecimal to base 8 etc etc..

Program/Code is in C/C++/linux/g++

#include <iostream>
#include <inttypes.h>
#include <math.h>

using namespace std;

void convertbase(char *inp, uint16_t inp_base, char *out, uint16_t out_base);
bool validateinp(char *inp, uint16_t inp_base);

main()
{

        char inp[64] = {'\0'};
        char out[64] = {'\0'};

        uint16_t inp_base, out_base;
        cout << "enter the base of input number (between 2 to 16): ";
        cin >> inp_base;

        if (inp_base < 2 || inp_base > 16) {
                cout << "output base not valid." << endl;
                return -1;
        }  

        cout << "enter input number: ";
        cin >> inp;

        bool isInpValid = validateinp(inp, inp_base);

        if (!isInpValid) {
                cout << "input num is not valid." << endl;
                return -1;
        }  

        cout <<"enter the base of output number (between 2 to 16): ";
        cin >> out_base;

        if (out_base < 2 || out_base > 16) {
                cout << "output base not valid." << endl;
                return -1;
        }  

        convertbase(inp, inp_base, out, out_base);   
}

bool validateinp(char *inp, uint16_t base) {
        char *ch = inp;
        uint32_t val;
        while (*ch != '\0') {
                val = (*ch > '9') ? ((*ch >= 'a') ? (*ch - 'a' + 10) : (*ch - 'A' + 10)) : (*ch - '0');
                if (val >= base) {
                       return false;
                }
                if (!((*ch >= 0 && *ch <= '9') || (*ch >= 'A' && *ch <= 'F' ) || (*ch >= 'a' && *ch <= 'f'))) {
                        return false;
                }
                ch++;
        }
        return true;
}

void convertbase(char *inp, uint16_t inp_base, char *out, uint16_t out_base)
{
        uint32_t val = 0, r = 0, i = 0, decimal = 0;
        char ch1, *ch = inp;

        while (*ch != '\0') {
                val = (*ch > '9') ? ((*ch >= 'a') ? (*ch - 'a' + 10) : (*ch - 'A' + 10)) : (*ch - '0');
                decimal = (decimal * inp_base) + val;
                ch++;
        }

        while (decimal > 0) {
                r = decimal % out_base;
                ch1 = (r >= 10) ? (r - 10 + 'A') : ('0' + r);
                out[i++] = ch1;
                decimal = decimal / out_base;
        }
        out[i] = '\0';

        for (r = 0; r < i/2; r++) {
                ch1 = out[r];
                out[r] = out[i - r - 1];
                out[i - r - 1] = ch1;
        }

        cout << "output is " << out << endl;
}