将一个N进制数转换成M进制数(源码)

来源:互联网 发布:姚明第一年数据 编辑:程序博客网 时间:2024/05/21 17:55

// 将一个N进制数转换成M进制数

#include <iostream>

#include <vector>

using namespace std;

 

void convert(int x, int n, int m)

{

    vector<int> vi;

    int y;

    while(x)

    {

        y = x % m;

        vi.push_back(y);

        x /= m;

    }

 

    vector<int>::reverse_iterator rit = vi.rbegin();

    for( ; rit!=vi.rend(); rit++)

    {

        if( *rit >= 10 )

        {

            char temp = *rit - 10 + 'A';

            cout << temp;

        }

        else

        {

            cout << *rit;

        }

    }

}

 

void convert(const char *str, int n, int m)

{

    if(*str == '/0') return;

    int x = 0;

    int y;

    while(*str != '/0')

    {

        x *= n;

        if((*str>='0') && (*str<='9'))

        {

            y = *str - '0';

        }

        else if( (*str>='A') && (*str<='F') )

        {

            y = 10 + *str - 'A';

        }

        else if( (*str>='a') && (*str<='f') )

        {

            y = 10 + *str - 'a';

        }

        else

        {

            cout << "error input" << endl;

            return;

        }

        if( y>=n )      // n进制数字不能大于n

        {

            cout << "error input" << endl;

            return;

        }

        x += y;

        str++;

    }

    convert(x, n , m);

}

 

int main(void)

{

    convert(1234, 10, 16);

    return 0;

}