How to convert binary to octal and vice-versa in C || Type 1 || Functions || C programming
In this program, we are going to see how to Convert Binary to Octal and Vice-versa (Type-1) in C Programming Language.

 

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void binaryToOctal()
{
    int oct = 0, dec = 0, i = 0;
    long long int bin;
    printf("Enter a binary number: ");
    scanf("%lld", &bin);
    // converting binary to decimal
    while (bin != 0)
    {
        dec += (bin % 10) * pow(2, i);
        ++i;
        bin /= 10;
    }
    i = 1;

    // converting to decimal to octal
    while (dec != 0)
    {
        oct += (dec % 8) * i;
        dec /= 8;
        i *= 10;
    }
    printf("%d in octal", oct);
}

void octalToBinary()
{
    int oct;
    int dec = 0, i = 0;
    long long bin = 0;

    printf("Enter an octal number: ");
    scanf("%d", &oct);
    // converting octal to decimal
    while (oct != 0)
    {
        dec += (oct % 10) * pow(8, i);
        ++i;
        oct /= 10;
    }
    i = 1;

    // converting decimal to binary
    while (dec != 0)
    {
        bin += (dec % 2) * i;
        dec /= 2;
        i *= 10;
    }
    printf("%lld in binary", bin);
}

int main()
{
    int operation;

    printf("-----Select the Operation------\n");
    printf("1. Binary to Octal\n2. Octal to Binary\n3. Exit\n");
    printf("Enter the corresponding number of Operation: ");
    scanf("%d", &operation);

    switch (operation)
    {
    case 1:
        binaryToOctal();
        break;

    case 2:
        octalToBinary();
        break;

    case 3:
        exit(0);

    default:
        printf("Wrong input");
    }

    return 0;
}

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post