【C/C++】任意进制转换

  进制转换:R进制->10进制;10进制->R进制、

 1 #include<bits/stdc++.h> 
 2 using namespace std;
 3 /*函数:r进制转换成10进制*/
 4 int rToTen(string n,int r){
 5     //将r进制转为10进制,n是该r进制的字符串表示
 6     int len = n.length();
 7     int ans = 0;
 8     int i = 0;
 9     while(i<len){
10         ans*=r;
11         ans+=n[i]-'0';
12         i++;
13     }
14     return ans;
15 }
16 
17 /*函数:十进制转任意进制*/ 
18 string tenToR(int n,int r){
19     //十进制n转r进制 ,返回字符串s 
20     char str[1005];
21     stack<int>s;
22     while(n){
23         s.push(n%r);
24         n = n/r;
25     }
26     int i = 0;
27     while(!s.empty()){
28         switch(s.top()){
29             case 10:
30                 str[i++] = 'A';
31                 break; 
32             case 11:
33                 str[i++] = 'B';
34                 break;
35             case 12:
36                 str[i++] = 'C';
37                 break;
38             case 13:
39                 str[i++] = 'D';
40                 break;
41             case 14:
42                 str[i++] = 'E';
43                 break;
44             case 15:
45                 str[i++] = 'F';
46                 break;
47             default:
48                 str[i++] = s.top()+'0';    
49         }
50         s.pop();
51     }
52     string st = str;
53     return st;
54 }
55 
56 
57 int main(){
58     cout<<rToTen("10010",2)<<endl;
59     cout<<tenToR(18,2)<<endl;
60 } 

 

posted @ 2018-08-27 11:20  pigcv  阅读(6836)  评论(0编辑  收藏  举报