0

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

这个这个

当我输入 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

4 回答 4

3

八进制数的数字都在范围内[0,7]。因此,58and59不是八进制数,您的方法应该会给出错误的结果

58计算为的原因101000是因为八进制数的第一位扩展为二进制数的前三位。5 = 101_2. 第二部分的故事相同,但是8 = 1000_2,所以你只能得到000部分。

另一种解释是8 = 0 (mod 8)(我在这里使用=符号表示一致性),因此两者80都将000使用您的代码以二进制形式计算。

最好的解决方案是进行一些输入验证。例如,在转换时,您可以检查以确保数字在范围内[0,7]

于 2013-06-25T17:46:51.147 回答
0

不能使用 58 或 59 作为输入值。看在基督的份上,它是八进制的。

有效数字为 0 到 7(含)。

于 2013-06-25T17:43:43.790 回答
0

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

小数 => 基数 = 10 => 从 0 到 9 的数字

十六进制 => 基数 = 16 => 0 到 15 的数字(嗯,0 到 F)

八进制 => 基数 = 8 => 0 到 7 的数字

于 2013-06-25T17:44:18.143 回答
0

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

于 2013-06-25T17:45:45.270 回答