C Program To Convert Octal To Binary

In this post, we will learn how to convert octal to binary using C Programming language.

C Program To Convert Octal To Binary

This program will take an octal number as input from the user and convert it into a binary number using a user-defined function. 

So, without further ado, let’s begin this tutorial.

C Program To Convert Octal To Binary

// C Program To Convert Octal To Binary
#include <stdio.h>
#include <math.h>

long octalToBinary(int num){
    int decimal = 0, i = 0;
    long binary = 0;
    
    while (num != 0){
        decimal = decimal + (num % 10) * pow(8, i);
        i++;
        num = num / 10;
    }
    i = 1;
    while (decimal != 0){
        binary = binary + (decimal % 2) * i;
        decimal = decimal / 2;
        i = i * 10;
    }
    return binary;
}

int main(){
    int num;
    
    // Asking for Input
    printf("Enter an octal number: ");
    scanf("%d", &num);
    
    printf("Equivalent Binary number is: %ld", octalToBinary(num));
    return 0;
}

Output

Enter an octal number: 25
Equivalent Binary number is: 10101

How Does This Program Work ?

    int num;

In this program, we have declared an int data type variable named as num.

    // Asking for Input
    printf("Enter an octal number: ");
    scanf("%d", &num);

Then, the user is asked to enter an octal number. The value of this octal number will get stored in the num named variable.

    printf("Equivalent Binary number is: %ld", octalToBinary(num));

Now, we call our custom defined function named octalToBinary which converts octal numbers into binary numbers.

long octalToBinary(int num){
    int decimal = 0, i = 0;
    long binary = 0;
    
    while (num != 0){
        decimal = decimal + (num % 10) * pow(8, i);
        i++;
        num = num / 10;
    }
    i = 1;
    while (decimal != 0){
        binary = binary + (decimal % 2) * i;
        decimal = decimal / 2;
        i = i * 10;
    }
    return binary;
}

This function will first convert the octal number into a decimal number, and then convert the decimal number into a binary number.

Conclusion

I hope after going through this post, you understand how to convert octal to binary using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *