n进制转m进制

#include<iostream>
#include<string.h>
using namespace std;

char in[1000],out[1000];
char *tmp;
int *size;
//10进制转m进制
void _10tom(int m,int num)
{
    //确保数为0时至少执行一次
    do
    {
        if (num%m >= 0&&num%m<=9)
            tmp[(*size)++] = num%m+'0';
        else tmp[(*size)++] = 'a' + num % m - 10;
        num /= m;
    } while (num != 0);

}
int pow(int x, int y)
{
    if (y == 0)
        return 1;
    int res=1;
    while (y)
    {
        if (y & 1)
            res *= x;
        x *= x;
        y >>= 1;
    }
    return res;
}
int  _nto10(int n, char* s)
{
    int res = 0, len = strlen(s);
    for (int i = len-1; i >=0; i--)
    {
        if ((s[i] >= 'a'&&s[i] <= 'z') )
            res+= (s[i] -'a'+10)*pow(n,len-i-1);
        else if ((s[i] >= 'A'&&s[i] <= 'Z'))
            res += (s[i] - 'A' + 10)*pow(n, len - i - 1);
        else res += (s[i] - '0')*pow(n, len - i - 1);

    }
    return res;
}
int main(){
    int a, b;
    while (cin >> a >> in >> b)
    {
        int ten = _nto10(a, in);
        tmp = out;
        int i = 0;
        size = &i;
        _10tom(b, ten);
        for (int j = i - 1; j>= 0; j--)
            cout << out[j];
        cout << endl;
    }
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/KingsCC/article/details/81781976