进制转换是计算机内部时时刻刻都在进行活动,本篇文章也是进制转换的算法介绍,不过不同的是我想利用ascll编码实现2到61之间任意进制的相互转换,更大进制的表示方法只不过是十六进制表示方法的延伸:用字母A到Z表示整数10到35,字母a到z表示整数36到61。这样就可以表示2到61之间的任意进制啦,为方便理解ascll表放在代码后面,可以自行查看。
下面直接给上代码:
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 void decToOther(int tmp, int b); 5 void otherToDec(int a, char str[], int b); 6 const int MAXSIZE = 10000; 7 int a, b; 8 char str[MAXSIZE]; 9 int main() 10 { 11 while (cin >> a >> str >> b) //a、s、b分别为目前的进制、待转换的内容、目标进制 12 otherToDec(a, str, b); //统一先转换为10进制 13 return 0; 14 } 15 16 void otherToDec(int a, char str[], int b) 17 {//任意进制转换为十进制 18 int tmp = 0; //tmp保存十进制的值 19 int c = 1; //初始化权值为1 20 for (int i = strlen(str) - 1; i >= 0; i--) 21 { 22 int x; //存放当前位的数字 23 if (str[i] >= 'A' && str[i] <= 'Z') //字母A~Z表示整数10~35 24 x = str[i] - 'A' + 10; 25 else if (str[i] >= 'a' && str[i] <= 'z') //字母a~z表示整数36~61 26 x = str[i] - 'a' + 36; 27 else 28 x = str[i] - '0'; 29 tmp = tmp + x * c; //累加将各个位上的值 30 c = c * a; //更新权值 31 } 32 decToOther(tmp, b); //由十进制转换为目标进制 33 } 34 35 void decToOther(int tmp, int b) 36 {//十进制转换为任意进制 37 int i = 0; 38 int s[MAXSIZE] = { 0 }; 39 while (tmp != 0) //十进制转换为目标进制算法,结果放到数组s中 40 { 41 s[i] = tmp % b; 42 tmp= tmp / b; 43 i++; 44 } 45 cout << a << "进制数" << str << "的" << b << "进制表示为:"; 46 for (; i > 0; i--) //利用ascll编码实现字母表示两位整数,并倒序输出转换结果 47 { 48 if (s[i - 1] > 9 && s[i - 1] <= 35) 49 cout << (char)(s[i - 1] + 55); //当s[i-1]为整数10时(char)(10+55)='A',输出'A' 50 else if (s[i - 1] > 35 && s[i - 1] <= 61) 51 cout << (char)(s[i - 1] + 61); //当s[i-1]为整数36时(char)(36+61)='a',输出'a' 52 else 53 cout << s[i - 1]; //个位数输出本身 54 } 55 cout << '\n'; 56 }
示例:
附:ascll表