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

时间:2022-10-27 22:22:23

1.八进制 –> 二进制
我这里采用了一种简单又高效的办法.
先把000 - 111 的二进制用二维数组存起来.
例如:八进制25–> 5对应101 2对应010 这时候只要把八进制分解为一位一位的,然后在数组中找对应的二进制即可,无论多大的八进制数,都可以很快的分解并找到对应的二进制数.

    char a[9][5] = { "000 ","001 ","010 ","011 ","100 ","101 ","110 ","111 " };
    int temp[20] = { 0 }; //存放每一位八进制数,例如:25 --> temp[0] = 5 ,temp[1] = 2
    int iLen = 0, i = 0, j = 0;
    while (oct) //分解八进制数
    {
        temp[i++] = oct % 10;
        if (temp[i - 1] == 8 || temp[i - 1] == 9)
            return -1; //八进制数只能是0-7
        oct /= 10;
    }
    do
    {
        --i;
        //例如:temp[1] = 2 --> a[2][] = "010 ",temp[0] = 5 --> a[5][] = "101 "
        while (j < 4) // --> bin = " 010 101" 
            bin[iLen++] = a[temp[i]][j++];
        j = 0;
    } while (i);
    return 0;
} 

注意:这个函数最大支持19位8进制数的转换
2.八进制 –> 十进制

这个也是权值相加即可.

long long OctToDec(long long oct)
{
    long long dec = 0;
    int p = 0, t = 0;
    while (oct)
    {
        t = oct % 10;
        dec += powl(8, p++)*t;
        if (t == 8 || t == 9)
            return -1;
        oct = oct / 10;
    }
    return dec;
}

注意:这个函数最大支持19位8进制数的转换

3.八进制 –> 16进制

只能通过间接转换了。

int OctToHex(long long oct, char* hex)
{
    long long dec = 0;
    char a[17] = "0123456789ABCDEF";
    char temp[30] = " ";
    int p = 0, t = 0, i = 0, j = 0;
    while (oct)               //八进制转换为十进制
    {
        t = oct % 10;
        dec += powl(8, p++)*t;
        if (t == 8 || t == 9)
            return -1;
        oct = oct / 10;
    }
    while (dec)               //十进制转换为十六进制 
    {
        temp[i++] = a[dec % 16];
        dec = dec >> 4;
    }
    while (i)
        hex[j++] = temp[--i]; //反转
    return 0;
}