大整数进制转换C++
时间: 2024-01-11 09:20:25 浏览: 88
非常经典的进制转换源代码
以下是C++实现大整数进制转换的示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 将字符串表示的数字转换为整数数组
void str2num(string str, int num[], int &len, int &dot_pos, int &dot_len) {
len = 0;
dot_pos = -1;
dot_len = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == '.') {
dot_pos = len;
} else {
num[len++] = str[i] - '0';
}
}
if (dot_pos != -1) {
dot_len = len - dot_pos - 1;
}
}
// 将整数数组转换为字符串表示的数字
string num2str(int num[], int len, int dot_pos, int dot_len) {
string str = "";
for (int i = 0; i < len; i++) {
str += num[i] + '0';
if (i == dot_pos) {
str += '.';
}
}
if (dot_pos == -1) {
str += '.';
}
for (int i = 0; i < dot_len; i++) {
str += '0';
}
return str;
}
// 将整数数组从from_base进制转换为to_base进制
void base_convert(int num[], int &len, int from_base, int to_base) {
int new_num[1000], new_len = 0;
while (len > 0) {
int r = 0;
for (int i = len - 1; i >= 0; i--) {
int t = r * from_base + num[i];
num[i] = t / to_base;
r = t % to_base;
}
new_num[new_len++] = r;
while (len > 0 && num[len - 1] == 0) {
len--;
}
}
for (int i = 0; i < new_len; i++) {
num[i] = new_num[new_len - i - 1];
}
len = new_len;
}
int main() {
string str;
int from_base, to_base;
cin >> str >> from_base >> to_base;
int num[1000], len, dot_pos, dot_len;
str2num(str, num, len, dot_pos, dot_len);
// 将整数部分从from_base进制转换为10进制
int int_num[1000], int_len = 0;
for (int i = 0; i < dot_pos; i++) {
int r = 0;
for (int j = int_len - 1; j >= 0; j--) {
int t = r * from_base + int_num[j];
int_num[j] = t % 10;
r = t / 10;
}
while (r > 0) {
int_num[int_len++] = r % 10;
r /= 10;
}
int_num[int_len++] = num[i];
}
reverse(int_num, int_num + int_len);
// 将小数部分从from_base进制转换为10进制
int dot_num[1000], dot_len = 0;
for (int i = dot_pos + 1; i < len; i++) {
int r = 0;
for (int j = 0; j < dot_len; j++) {
int t = r * from_base + dot_num[j];
dot_num[j] = t % 10;
r = t / 10;
}
while (r > 0) {
dot_num[dot_len++] = r % 10;
r /= 10;
}
dot_num[dot_len++] = num[i];
}
// 将整数部分和小数部分分别从10进制转换为to_base进制
base_convert(int_num, int_len, 10, to_base);
base_convert(dot_num, dot_len, 10, to_base);
// 将整数部分和小数部分合并为一个数组
for (int i = 0; i < int_len; i++) {
num[i] = int_num[i];
}
num[int_len++] = -1;
for (int i = 0; i < dot_len; i++) {
num[int_len++] = dot_num[i];
}
// 将整个数组转换为字符串表示的数字
str = num2str(num, int_len, dot_pos, dot_len);
cout << str << endl;
return 0;
}
```
阅读全文