C++转换十进制数到任何其它进制的函数
#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
}
