C Program to Convert Binary Number to Octal and vice-versa

This post helps the conversion of the binary number and octal and vice-versa using the C programming language.

C Program to Convert Binary Number to Octal and vice-versa

#include<stdio.h>
#include<math.h>
int convert(long long bin);
int main() 
{
    long long bin;
    printf("Enter a binary number: ");
    scanf("%lld", &bin);
    printf("%lld in binary = %d in octal", bin, convert(bin));
    return 0;
}
int convert(long long bin) 
{
    int octal=0,deci=0,i=0;
    //converting binary to decimal
    while (bin != 0) 
    {
        deci += (bin % 10)*pow(2, i);
        ++i;
        bin /= 10;
    }
    //converting to decimal to octal
    i = 1;
    while(deci != 0) 
    {
        octal+=(deci % 8) * i;
        deci /= 8;
        i *= 10;
    }
    return octal;
}

Output

Explanation

We start the program by initializing the function and then use the main function to get the value of variable long long bin(%lld). The value revised from the user is for the conversion of the binary number to octal and vice versa.

int convert(long long bin);
int main() 
{
    long long bin;
    printf("Enter a binary number: ");
    scanf("%lld", &bin);
    printf("%lld in binary = %d in octal", bin, convert(bin));
    return 0;
}

Now we call the function to do the conversion, the value entered by the user first gets converted from binary to decimal.

int convert(long long bin) 
{
    int octal=0,deci=0,i=0;
    //converting binary to decimal
    while (bin != 0) 
    {
        deci += (bin % 10)*pow(2, i);
        ++i;
        bin /= 10;
    }

After the value is converted as decimal, it now gets converted from decimal to octal, to complete the process of conversion of binary numbers to octal.

//converting to decimal to octal
    i = 1;
    while(deci != 0) 
    {
        octal+=(deci % 8) * i;
        deci /= 8;
        i *= 10;
    }
    return octal;
}

Now we get the converted desired output.

%d