C++中可以使用以下算法来实现进制转换:
#include <iostream>
#include <string>
std::string decToBase(int num, int base) {
std::string result = "";
while (num > 0) {
int rem = num % base;
result = (char)(rem < 10 ? rem + '0' : rem + 'A' - 10) + result;
num /= base;
}
return result;
}
int main() {
int num = 123;
int base = 16;
std::string result = decToBase(num, base);
std::cout << result << std::endl;
return 0;
}
#include <iostream>
#include <string>
int baseToDec(const std::string& num, int base) {
int result = 0;
int power = 1;
for (int i = num.length() - 1; i >= 0; i--) {
int digit = (num[i] >= '0' && num[i] <= '9') ? (num[i] - '0') : (num[i] - 'A' + 10);
result += digit * power;
power *= base;
}
return result;
}
int main() {
std::string num = "7B";
int base = 16;
int result = baseToDec(num, base);
std::cout << result << std::endl;
return 0;
}
以上示例分别实现了十进制转其他进制和其他进制转十进制的算法,你可以根据实际需求,选择合适的算法来进行进制转换。