C语言,进制转换之二进制转十六进制,完整代码

#include "iostream"
using namespace std;
#define MAX 50
int _2to16()//二转十六
{
    cout << "请输入二进制数,并以‘$’结束:"; 
    char elem2[MAX];
    int flag = 1;
    char ch;
    int i = 0;
    while (flag)
    {
        cin >> ch;
        if (ch != '$')
        {
            elem2[i] = ch;
            i++;
        }
        else
        {
            flag = 0;
        }
    }
    int length = i;
    int n = 0;
    int sum = 0;
    int product = 0;
    if (length % 4 != 0)//将缺位的二进制码用0补齐
    {
        int n = 4 - length % 4;
        int i = 0;
        for (i = length - 1; i >= 0; i--)
            elem2[i + n] = elem2[i];
        length += n;
        for (i = 0; i < n; i++)
            elem2[i] = '0';
        cout << "补齐之后的内容是:" << endl;
        for (i = 0; i < length; i++)
            cout << elem2[i]<<" ";
        cout << endl;
    }
    for (n = 0; n < length; n++)//判断是否是二进制数
    {
        if ('1' == elem2[n] || '0' == elem2[n])
            sum++;
    }
    if (sum == length)
    {
        char elem16[MAX];
        int r = 0;
        int m = 0;
        int p = 0;
        int q = 0;
        for (m = length - 1; m >= 0; m--)
        {
            q = elem2[m] - '0';
            product += q * pow(2, p);
            p++;
            if (4 == p)
            {
                if (product>9)
                elem16[r] = product+55;//输出A...F范围
                else
                {
                    elem16[r] = product+48;//输出0...9范围
                }
                r++;
                p = 0;
                product = 0;
            }
        }
        int j = 0;
        cout << "对应的十六进制数是:OX";
        for (j = r - 1; j >= 0; j--)
            cout << elem16[j];
        cout << endl;

    }
    else
    {
        cout << "你输入的不是二进制数!" << endl;
    }
    return 0;
}

你可能感兴趣的:(c,c语言,进制转换,二进制转十六进制)