- /***** from进制的大数转换为to进制 *****/
- #include <cstring>
- #include <string>
- string rev(string &s) /*字符串逆序*/
- {
- int i;
- string temp = "";
- for (i = s.length() - 1; i >= 0; i--)
- temp += s.at(i);
- return temp;
- }
- int getNum(char str) {
- int num;
- if (isdigit(str))
- num = str - '0';
- else if (str >= 'A' && str <= 'Z')
- num = str - 'A' + 10;
- else
- num = str - 'a' + 36;
- return num;
- }
- char getChar(int num) {
- char index[62] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
- 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
- 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
- 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
- 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
- return index[num];
- }
- /*分别表示被除数,除数,商、余数及被除数的进制*/
- void Divide(string ÷nd, int to, string "ient, int *remainder,
- int from) {
- int i;
- int flag = 0; /*用来判断最后的商是否全为0*/
- int curDividend = 0; /*当前的被除数*/
- quotient = "";
- *remainder = 0;
- for (i = 0; i < dividend.length(); i++) {
- curDividend = (*remainder) * from + getNum(dividend.at(i));
- if (curDividend < to) {
- quotient += "0";
- *remainder = curDividend;
- } else {
- quotient += getChar(curDividend / to);
- *remainder = curDividend % to;
- }
- }
- /*对商进行处理,去除前导0*/
- for (i = 0; i < quotient.length(); i++) {
- if (quotient.at(i) != '0') {
- flag = 1;
- quotient = quotient.erase(0, i);
- /*删除从0开始的i个字符,返回新的字符串*/
- break;
- }
- }
- if (flag == 0) /*商全为0*/
- quotient = "0";
- }
- /*分别表示原进制大数、转换结果、原进制及目标进制,仅限在62进制以内*/
- void Change(string &a, string &b, int from, int to) {
- int remainder; /*余数*/
- string quotient; /*商*/
- b = ""; /*初始化*/
- Divide(a, to, quotient, &remainder, from);
- while (quotient.compare("0") != 0) {
- b += getChar(remainder);
- a = quotient;
- Divide(a, to, quotient, &remainder, from);
- }
- b += getChar(remainder);
- b = rev(b); /*逆序*/
- }
- /***** from进制的大数转换为to进制 *****/
- //该片段来自于http://www.codesnippet.cn/detail/200820135239.html
来源: http://www.codesnippet.cn/detail/200820135239.html