Convert Decimal to any base

Freaky_Chris 0 Tallied Votes 3K Views Share

The following code snippet can be used to convert a decimal integer into any base from 2-16. This is a simple piece of code and I hope t proves useful to people.

I see many people posting Decimal to Hex. or Decimal to binary, non any better than the next. I'm not saying this is the best method, but I think it's small size, clarity, and flexibility (not restricted to converting to one base) makes it a nice snippet.

#include <iostream>
#include <string>

std::string conv(int decimal, int base);

int main(void){
    std::cout << "Binary\tOctal\tDecimal\tHexidecimal"<< std::endl;
    std::cout << conv(50, 2) << '\t' << conv(50, 8) << '\t';
    std::cout << conv(50, 10) << '\t' << conv(50, 16);

    return 0;

std::string conv(int decimal, int base){
    if(decimal == 0) return "0";
    char NUMS[] = "0123456789ABCDEF"; // Characters that may be used
    std::string result = ""; // Create empty string ready for data to be appended
        // Append the appropriate character in NUMS based on the equation decimal%base
        decimal /= base; // Calculate new value of decimal
    }while(decimal != 0); // Do while used for slight optimisation
    return std::string(result.rbegin(), result.rend());
    // using std::string() constructer with iterators to reverse the string
ddanbe 2,724 Professional Procrastinator Featured Poster

Very well done!

hehehe01 0 Newbie Poster

Can you please convert these to C?
My knowledge in C++ is not that great.

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.