Pergunta

I have a code in C++ which convert 2 digits octal number to binary number. For testing validity of the code I used several online conversion site like

this and this

When I enter 58 or 59 in as an octal value it says invalid octal values but when I enter 58 in my code it gives binary number as - 101000. Again for testing I enter 101000 as binary number in above website's calculator then they gives me result 50 as octal value.

I need some explanation why this is so.

Here is the C++ code -

#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;
}
Foi útil?

Solução

Octal numbers have digits that are all in the range [0,7]. Thus, 58 and 59 are not octal numbers, and your method should be expected to give erroneous results.

The reason that 58 evaluates to 101000 is because the first digit of the octal number expands to the first three digits of the binary number. 5 = 101_2. Same story for the second part, but 8 = 1000_2, so you only get the 000 part.

An alternate explanation is that 8 = 0 (mod 8) (I am using the = sign for congruency here), so both 8 and 0 will evaluate to 000 in binary using your code.

The best solution would be to do some input validation. For example, while converting you could check to make sure the digit is in the range [0,7]

Outras dicas

You cannot use 58 or 59 as an input value. It's octal, for Christ's sake.

Valid digits are from 0 to 7 inclusive.

If you're encoding a number in base 8, none of the octets can be 8 or greater. If you're going to do the code octet by octet, there needs to be a test to see whether the octet is 8 or 9, and to throw an error. Right now your code isn't checking this so the 8 and 9 are overflowing to 10.

58 and 59 aren't valid octal values indeed ... the maximum digit you can use is yourbase-1 :

decimal => base = 10 => Digits from 0 t 9

hexadécimal => base = 16 => Digits from 0 to 15 (well, 0 to F)

Octal => base = 8 => Digits from 0 to 7

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top