C program to convert Octal to Binary number

In this article, we are going to learn the C program to convert Octal to an equivalent Binary number. 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

C program to convert Octal number system to Binary number


#include <stdio.h>
#define SIZE 16
 
int main()
{
    char octNum[SIZE];
    int i = 0;
 
    printf("Please enter an octal number: ");
    scanf("%s", octNum);
    
    printf("Binary Equivalent to Octal number %s is \n", octNum);

    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:
            printf(" 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

C program to convert Octal number system to Binary number system


In the above program, we made 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.

In this example, we are taking a number input from the user and converting it into a binary number

 
#include <stdio.h>

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

    long long octNum, tmpOctNo;
    long long binNum, place;
    int rem;
    
   
    printf("Enter any Octal number: ");
    scanf("%lld", &octNum);

    tmpOctNo = octNum;

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

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

       
            tmpOctNo = tmpOctNo/10;

            place =place * 1000;
         }
	printf("Binary Equivalent to Octal number %lld is %lld\n", octNum,binNum);
     
    return 0;
}

Output

Enter any Octal number: 123
Binary Equivalent to Octal number 123 is 1010011