c++大整数进制转换函数
时间: 2023-08-13 18:11:59 浏览: 86
以下是一个简单的C++函数,用于将大整数从一种进制转换为另一种进制:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
string convertBase(string num, int oldBase, int newBase) {
int decimalNum = 0;
int power = 1;
bool isNegative = (num[0] == '-');
// Convert to decimal base
for (int i = num.size() - 1; i >= isNegative ? 1 : 0; i--) {
int digitValue = isdigit(num[i]) ? num[i] - '0' : num[i] - 'A' + 10;
decimalNum += digitValue * power;
power *= oldBase;
}
// Convert to new base
string newNum;
while (decimalNum > 0) {
int remainder = decimalNum % newBase;
char digitChar = (remainder < 10) ? remainder + '0' : remainder - 10 + 'A';
newNum += digitChar;
decimalNum /= newBase;
}
if (newNum.empty()) {
newNum = "0";
}
if (isNegative) {
newNum += '-';
}
// Reverse the result and return
reverse(newNum.begin(), newNum.end());
return newNum;
}
int main() {
string num;
int oldBase, newBase;
cout << "Enter a number: ";
cin >> num;
cout << "Enter the old base: ";
cin >> oldBase;
cout << "Enter the new base: ";
cin >> newBase;
cout << num << " in base " << oldBase << " is " << convertBase(num, oldBase, newBase) << " in base " << newBase << endl;
return 0;
}
```
该函数使用两个参数:要转换的数字和两个进制值(旧进制和新进制)。它首先将该数字转换为十进制,然后将其转换为新进制。在转换过程中,该函数会使用余数和商的计算来获得新进制下的每一位。最后,新数被反转并返回。
请注意,此函数仅适用于非负整数。如果输入数字为负数,则应在函数中进行适当的更改。
阅读全文