八进制到二进制转换的混乱

时间:2013-06-25 17:39:23

标签: c++ number-systems

我有一个C ++代码,它将2位八进制数转换为二进制数。为了测试代码的有效性,我使用了几个在线转换网站,如

thisthis

当我输入58或59作为八进制值时,它表示无效的八进制值但是当我在我的代码中输入58时,它给出二进制数为 - 101000.再次进行测试我在上面的网站的计算器中输入101000作为二进制数然后他们给我结果50作为八进制值。

我需要一些解释为什么会这样。

这是C ++代码 -

#include <iostream.h>
#include <conio.h>
void octobin(int);

void main()
{
    clrscr();
    int a;
    cout << "Enter a 2-digit octal number : ";
    cin>>a;
    octobin(a);
    getch();
}
void octobin(int oct)
{
    long bnum=0;
    int A[6];
    //Each octal digit is converted into 3 bits, 2 octal digits = 6 bits.
    int a1,a2,quo,rem;
    a2=oct/10;
    a1=oct-a2*10;
    for(int x=0;x<6;x++)
    {
        A[x]=0;
    }
    //Storing the remainders of the one's octal digit in the array.
    for (x=0;x<3;x++)
    {
        quo=a1/2;
        rem=a1%2;
        A[x]=rem;
        a1=quo;
    }
    //Storing the remainders of the ten's octal digit in the array.
    for(x=3;x<6;x++)
    {
        quo=a2/2;
        rem=a2%2;
        A[x]=rem;
        a2=quo;
    }
    //Obtaining the binary number from the remainders.
    for(x=x-1;x>=0;x--)
    {
        bnum*=10;
        bnum+=A[x];
    }
    cout << "The binary number for the octal number " << oct << " is " << bnum << "." << endl;
}

4 个答案:

答案 0 :(得分:3)

八进制数字的数字都在[0,7]范围内。因此,5859 不是八进制数,并且您的方法应该会产生错误的结果。

58求值为101000的原因是因为八进制数的第一个数字扩展到二进制数的前三位。 5 = 101_2。第二部分的情况相同,但是8 = 1000_2,因此您只能获得000部分。

另一种解释是8 = 0 (mod 8)(我在这里使用congruency=符号),因此80都会评估为{使用您的代码以二进制文件{1}}。

最好的解决方案是进行一些输入验证。例如,在转换时,您可以检查以确保数字位于000

范围内

答案 1 :(得分:0)

您不能使用58或59作为输入值。为基督的缘故,它是八进制的。

有效数字从0到7,包括在内。

答案 2 :(得分:0)

58和59确实无效的八进制值...您可以使用的最大数字是yourbase-1:

decimal =&gt; base = 10 =&gt;数字从0 t 9

hexadécimal=&gt; base = 16 =&gt;数字从0到15(好,0到F)

Octal =&gt; base = 8 =&gt;数字从0到7

答案 3 :(得分:0)

如果您正在编码基数为8的数字,则所有八位字节都不能为8或更大。如果您要按八位位组执行代码八位字节,则需要进行测试以查看八位字节是8还是9,并抛出错误。现在你的代码没有检查这个,所以8和9溢出到10。