核心思想为:将旧的进制先转换为十进制的数字,然后再将十进制的数字转换为新的进制。
例如:将7进制的23转换为9进制的数字为??
7进制-->10进制 23 = 3*7^0 + 2 * 7^1 = 3 +14 = 17;
10进制-->9进制 17 % 9 = 8; 17/9 = 1;
1 %9 = 1; 1/9 = 0;
核心公式为:x = n % m ; n = n / m; (n为十进制数,m为将要转换的进制数,x为取余后的数)
最后将余数反向输出,也可以利用栈的“先进后出”的特点进行对余数的保存。
代码如下:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <queue>
using namespace std;
int main()
{
int old,now;//old代表本来所属禁止,now代表将要转换的进制
string data;//使用data来存放原进制类型的数据
char data_new[100];//存放要转换的进制的数据
cin >> old >> data >> now;
int num_10 = 0;//作为中间变量,存储动态的中间十进制
int value = 1;//将value作为权重
for(int i=data.length()-1;i>=0;i--){//将原进制转换为十进制
int temp=0;
if(data[i]>='0'&&data[i]<='9')
{
temp=data[i]-'0';
}
else
{
temp=data[i]-'A'+10;//求出该位对应的10进制数
}
num_10 += temp*value; //数字加权重
value*=old;
}
cout<<"10进制数字为:"<< num_10 <<endl;
int new_cnt=0;//存储新类型中字符的个数
do{
int temp=0;
temp=num_10%now;
num_10/=now;
if(temp>=10)
data_new[new_cnt++]=temp-10+'A';
else
data_new[new_cnt++]=temp+'0';
}while(num_10);
cout << now <<"进制数据为:";
for(int i= new_cnt-1;i>=0;i--)
cout<<data_new[i];
cout<<endl;
return 0;
}