进制转换的代码2~16进制任意转换。
注释应该够详细能讲清楚。
总归就是先变成10进制再转换
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
string convert(int a, string& s, int b)
{
long val, dcount, digit;
char result[100000], c;
string ans;
val = 0;
for(int i=0; i<(int)s.size(); i++) {
if(isdigit(s[i]))//判断是不是数字,有些进制下不是数字
val = val * a + s[i] - '0';//是直接加
else
val = val * a + toupper(s[i]) - 'A' + 10;//不是的变成数字 toupper()函数来变
}//变成十进制
dcount = 0;
while(val) {
digit = val % b;
val /= b;
result[dcount++] = ((digit >= 10) ? 'A' - 10 : '0') + digit;//大于等于十的变字母储存,不是的按数字储存
}//十进制转换存储通过取余操作
if(dcount == 0) {
result[dcount++] = '0';
result[dcount] = '\0';//如果为0就是0
} else
result[dcount] = '\0';//字符串的结尾
for(int i=0, j=dcount-1; i<j; i++, j--) {
c = result[i];
result[i] = result[j];
result[j] = c;
}//反向存储一波之前的是从个位开始存的
ans = result;
return ans;
}
int main()
{
int t;cin>>t;
while(t--){
string s;
cin>>s;
int a,b;cin>>a>>b;//从a-b进制
cout << convert(a, s, b) << endl;}//进行转换
return 0;
}