Converting from any Radix to another

Freaky_Chris 0 Tallied Votes 672 Views Share

This snippet can be used to convert from bases between 2 & 16 to base between 2 & 16.

This is an extension on converting decimal to any base snippet found here: http://www.daniweb.com/code/snippet1067.html

(By no means is this the best method of doing this, but provides rather a nice way)

#include <iostream>
#include <string>

std::string conv(std::string number, int startBase, int endbase);
long long power(int num, int pow);

int main(void){
    std::string binary = "11010010";
    std::cout << "Start Base: Binary (" << binary << ")" << std::endl;
    std::cout << "Octal:\t\t" << conv(binary, 2, 8) << std::endl;
    std::cout << "Decimal:\t" << conv(binary, 2, 10) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(binary, 2, 16) << std::endl << std::endl;

    std::string octal = "81";
    std::cout << "Start Base: Octal (" << octal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(octal, 8, 2) << std::endl;
    std::cout << "Decimal:\t" << conv(octal, 8, 10) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(octal, 8, 16) << std::endl << std::endl;

    std::string decimal = "41";
    std::cout << "Start Base: Decimal (" << decimal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(decimal, 10, 2) << std::endl;
    std::cout << "Octal:\t\t" << conv(decimal, 10, 8) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(decimal, 10, 16) << std::endl << std::endl;

    std::string hexadecimal = "A9";
    std::cout << "Start Base: Hexadecimal (" << hexadecimal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(hexadecimal, 16, 2) << std::endl;
    std::cout << "Octal:\t\t" << conv(hexadecimal, 16, 8) << std::endl;
    std::cout << "Decimal:\t" << conv(hexadecimal, 16, 10) << std::endl << std::endl;
    return 0;
}

std::string conv(std::string number, int startBase, int endBase){
    if(startBase > 16 || endBase > 16) return "BASE ERROR";
    char NUMS[] = "0123456789ABCDEF";
    std::string result = "";
    int temp = 0, x;
    bool found = false;
    for(int i = 0; i < number.length(); i++){
        for(x = 0; x < startBase; x++){
            if(NUMS[x] == number[number.length()-(i+1)]){
                found = true;
                break;
            }
        }
        if(!found) return "NUMBER ERROR";
        temp += (x*power(startBase, i));
    }
    do{
        result.push_back(NUMS[temp%endBase]);
        temp /= endBase;
    }while(temp != 0);
    return std::string(result.rbegin(), result.rend());
}

long long power(int num, int pow){
    if(pow == 0) return 1;
    return num*power(num, pow-1);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.