基础的进制转换模板
支持10进制以上,大于十进制的位数用大写字母表示
首先 输入一个数字和其进制,就能输出其数字的十进制数。
再输入一个十进制数字和其进制,就能输出其数字的进制数。
第一次输入数字的时候,可以输入大写英文字母来表示大于10的数字。
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
void to_tens(string one,int radix){//转换成十进制
int res = 0;
int times = 1;
for(int i = one.size() - 1;i >= 0;i --){
int nums = 0,now;
if(one[i] >= '0' && one[i] <= '9')
nums = one[i] - '0';
else if(one[i] >= 'A' && one[i] <= 'Z')
nums = one[i] - 'A' + 10;
now = nums * times;
times *= radix;
res += now;
}
cout << res << endl;
}
void to_radix(int x,int radix){//转换成该进制的输出
string res;
do{
int now = x % radix;
x /= radix;
if(now >= 10) res.push_back(now - 10 + 'A');
else res.push_back('0' + now);
}while(x != 0);
reverse(res.begin(),res.end());
cout << res << endl;
}
int main()
{
string ss;
cin >> ss;
int x;
cin >> x;//x是进制
to_tens(ss,x);
int tens;
cin >> tens >> x;
to_radix(tens,x);
return 0;
}
//
//sample input:
// 10101110 2
// 174 2
//
//sample output:
// 174
// 10101110