c++特别大的整数进制转换函数
时间: 2023-11-25 09:08:47 浏览: 74
C++写的大整数计算器
5星 · 资源好评率100%
C++中可以使用标准库中的`stringstream`来实现大整数进制转换,具体实现方法如下:
```c++
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
// 将十进制数转换为其他进制
string dec_to_any(int num, int base) {
stringstream ss;
string result = "";
bool negative = false;
if (num < 0) {
negative = true;
num = -num;
}
while (num) {
int remainder = num % base;
if (remainder < 10) {
ss << remainder;
} else {
ss << (char)('A' + remainder - 10);
}
num /= base;
}
ss >> result;
if (negative) {
result += "-";
}
reverse(result.begin(), result.end());
return result;
}
// 将其他进制数转换为十进制
int any_to_dec(string num, int base) {
int result = 0;
bool negative = false;
if (num[0] == '-') {
negative = true;
num.erase(num.begin());
}
for (int i = 0; i < num.size(); i++) {
int digit = 0;
if (num[i] >= '0' && num[i] <= '9') {
digit = num[i] - '0';
} else {
digit = num[i] - 'A' + 10;
}
result = result * base + digit;
}
if (negative) {
result = -result;
}
return result;
}
int main() {
int num = 1234567890;
int base1 = 2, base2 = 16;
string result1 = dec_to_any(num, base1);
int result2 = any_to_dec(result1, base1);
string result3 = dec_to_any(num, base2);
int result4 = any_to_dec(result3, base2);
cout << "num: " << num << endl;
cout << "base " << base1 << ": " << result1 << endl;
cout << "back to decimal: " << result2 << endl;
cout << "base " << base2 << ": " << result3 << endl;
cout << "back to decimal: " << result4 << endl;
return 0;
}
```
在上述代码中,`dec_to_any`函数将一个十进制数转换为其他进制的数,`any_to_dec`函数将其他进制的数转换为十进制数,其中`base`参数表示需要转换的进制。
代码中使用了`stringstream`来将数字转换为字符串,`reverse`函数用于翻转字符串。
阅读全文