C++ program to convert Octal to Binary

In this article, we are going to learn how to convert an Octal number to an equivalent Binary number in C++. Here we are going to learn about two number systems one is binary and another is octal. Binary numbers are base 2 numbers and represented in 0s and 1s. Octal numbers are base 8 numbers and are represented in numbers from 0 to 7.The binary to octal equivalent number table is given below:

Binary NumberOctal Number
0000
0011
0102
0113
1004
1015
1106
1117
binary to octal number table:

1. C++ program to convert Octal to Binary number


#include<iostream>
using namespace std;
#define SIZE 16
 
int main()
{
    char octNum[SIZE];
    int i = 0;
 
    cout<< "Please enter an octal number: ";
    cin >> octNum;
    
    cout <<"Binary Equivalent to Octal number " << octNum << " is:"; 

    while (octNum[i])
    {
        switch (octNum[i])
        {
        case '0':
            printf("000");
            break;
        case '1':
            printf("001"); 
            break;
        case '2':
            printf("010"); 
            break;
        case '3':
            printf("011"); 
            break;
        case '4':
            printf("100"); 
            break;
        case '5':
            printf("101"); 
            break;
        case '6':
            printf("110"); 
            break;
        case '7':
            printf("111"); 
            break;
        default:
            cout << " Not Possible! Because your input is Wrong";
            return 0;
        }
        i++;
    }
    return 0;
}

Output

Please enter an octal number: 4
Binary Equivalent to Octal number 4 is:100

Please enter an octal number: 9
Binary Equivalent to Octal number 9 is: Not Possible! Because your input is Wrong

2. C++ Program to Convert Octal to Binary


In the above program, we made the use of a switch statement and it works only for basic octal numbers.
In this below example, we are expanding this conversion logic for any size of the octal number.

#include<iostream>
using namespace std;

int main()
{
    int BINCONSTANTS[] = {0, 1, 10, 11, 100, 101, 110, 111};

    long long octNum, tmpOctNo;
    long long binNum, place;
    int rem;
    
   
    cout<< "Please enter an octal number: ";
    cin >> octNum;

    tmpOctNo = octNum;
    binNum = 0;
    place  = 1;
    
    while(tmpOctNo > 0)
    { 
        rem = tmpOctNo % 10;

       	binNum = (BINCONSTANTS[rem] * place) + binNum;

        tmpOctNo = tmpOctNo/10;

        place =place * 1000;
      }
	
      cout <<"Binary Equivalent to Octal number " << octNum << " is:" << binNum; 
     
    return 0;
}

Output

Please enter an octal number: 4
Binary Equivalent to Octal number 4 is:100

Please enter an octal number: 123
Binary Equivalent to Octal number 123 is:1010011