# Convert Decimal to any base

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.

1,388 Views
``````#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
do{
result.push_back(NUMS[decimal%base]);
// 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

Very well done!

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

Be a part of the DaniWeb community

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