如何将十六进制转换为、二进制、八进制、十进制

1.十六进制 –> 二进制

void HexToBin(char* hex, char* bin, int n = 20)
{
    char a[17][6] = {
        "0000 ","0001 ","0010 ","0011 ",
        "0100 ","0101 ","0110 ","0111 ",
        "1000 ","1001 ","1010 ","1011 ",
        "1100 ","1101 ","1110 " ,"1111 " };
    int* temp = (int*)malloc(sizeof(int)*n);
    memset(temp, 0, n * 4);
    char* h = hex;
    int i = 0, j = 0, k = 0, g = 0;
    while (*h)                      //把十六进制的每一位转换为整数
    {
        char ch = *h;
        if (ch == 'A')temp[i++] = 10;
        else if (ch == 'B') temp[i++] = 11;
        else if (ch == 'C') temp[i++] = 12;
        else if (ch == 'D') temp[i++] = 13;
        else if (ch == 'E') temp[i++] = 14;
        else if (ch == 'F') temp[i++] = 15;
        else temp[i++] = *h - '0';
        h++;
    }
    do
    {
        while (j < 5)
            bin[k++] = a[temp[g] % 16][j++];
        j = 0;
    } while (i>++g);
    free(temp);
}

这个和二进制转十六进制的思想是一样的。

2.十六进制 –> 八进制

long long HexToOct(char* hex)
{
    long long oct = 0;
    long long dec = 0;
    char* h = hex;
    int p = 0, q = 0, i = 0, g = 0;
    int temp[30] = { 0 };
    while (*h++) ++p;  //calc hex arrary length
    h = hex;
    while (*h)                          //把十六进制的每一位转换为整数
    {
        char ch = *h;
        if (ch == 'A')temp[i++] = 10;
        else if (ch == 'B') temp[i++] = 11;
        else if (ch == 'C') temp[i++] = 12;
        else if (ch == 'D') temp[i++] = 13;
        else if (ch == 'E') temp[i++] = 14;
        else if (ch == 'F') temp[i++] = 15;
        else temp[i++] = *h - '0';
        h++;
    }
    i = 0;
    while (p)                       //十六进制 --> 十进制
        dec += powl(16, --p)*temp[i++];//因为powl的缘故,十六进制不能太大
    memset(temp, 0, sizeof(temp));
    i = 0;
    while (dec)                     //十进制 --> 八进制
    {
        temp[i++] = (dec % 8);
        dec = dec >> 3;
    }
    while (q < i)                   
        oct += powl(10, q++)*temp[g++];
    return oct;
}

注意:最大支持12位的16进制

3.十六进制转换为十进制
直接求权值和即可

long long HexToDec(char* hex)
{
    long long dec = 0;
    int temp[30] = { 0 };
    char* h = hex;
    int i = 0, p = 0;
    while (*h++) ++p;  
    while (*hex)                               
    {
        char ch = *hex;
        if (ch == 'A')temp[i++] = 10;
        else if (ch == 'B') temp[i++] = 11;
        else if (ch == 'C') temp[i++] = 12;
        else if (ch == 'D') temp[i++] = 13;
        else if (ch == 'E') temp[i++] = 14;
        else if (ch == 'F') temp[i++] = 15;
        else temp[i++] = *hex - '0';
        hex++;
    }
    i = 0;
    while (p)                       
        dec += powl(16, --p)*temp[i++];
    return dec;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值