您的位置:首页 > 其它

进制转换--待整理

2017-02-14 16:21 363 查看
#include <iostream>
#include <math.h>
#include <algorithm>
#include <cstring>
#include <string>
#define maxSize 10005
#define ascii_0 48
#define A 65

using namespace std;

//字符串 转为 十进制
int toInt(string tar) {
int len = tar.size();
int sum = 0,temp;
for (int i = 0; i < len; i++) {
temp = tar[i] - ascii_0;
sum = sum * 10 + temp;
}
return sum;
}

//十进制 转为 其他进制
void exchFrom_10(string tar, int hex) {
int b, temp, top = -1,dec = 10, stack[maxSize];
memset(stack, 0, sizeof(stack));
int a = toInt(tar);

while (a >= hex) {
b = a % hex;
a = a / hex;
stack[++top] = b;
}
stack[++top] = a;
if (hex < dec) dec = hex;

while (top >= 0) {//输出  注意方向,不要倒着输出
if (stack[top] >= dec) { temp = A + (stack[top] - dec); cout << (char)temp; }
else cout << stack[top];
top--;
}
}

//其他进制 转为 十进制
void exchTo_10(string tar, int hex) {
int dec = 10,sum = 0, temp, carry = 0;
int a[maxSize];
int len = tar.size();
memset(a, 0, sizeof(a));
reverse(tar.begin(), tar.end());//逆置

for (int i = 0; i < len; i++) {//高精度 转换
if (tar[i] >= A)//字符为 字母时
temp = tar[i] - A + dec;
else
temp = tar[i] - ascii_0;

sum = carry + temp;
a[i] = sum % dec;
carry = sum / dec;
}
for (int i = len - 1; i >= 0; i--)//输出
cout << a[i];
cout << endl;
}

int main() {

string wish;//数字以 字符串形式 读入
int hex;
cin >> wish >> hex;
//exchFrom_10(wish, hex);
exchTo_10(wish, hex);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: