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

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

In this example, you will learn to convert binary number to octal and octal number to binary manually by creating a user-defined function.
To understand this example, you should have the knowledge of following C programming topics:
  • C Programming Functions
  • C Programming User-defined functions

Example 1: Program to Convert Binary to Octal

In this program, we will first convert binary number to decimal. Then, the decimal number is converted to octal.
#include <stdio.h>
#include <math.h>

int convertBinarytoOctal(long long binaryNumber);
int main()
{
    long long binaryNumber;

    printf("Enter a binary number: ");
    scanf("%lld", &binaryNumber);

    printf("%lld in binary = %d in octal", binaryNumber, convertBinarytoOctal(binaryNumber));

    return 0;
}

int convertBinarytoOctal(long long binaryNumber)
{
    int octalNumber = 0, decimalNumber = 0, i = 0;

    while(binaryNumber != 0)
    {
        decimalNumber += (binaryNumber%10) * pow(2,i);
        ++i;
        binaryNumber/=10;
    }

    i = 1;

    while (decimalNumber != 0)
    {
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }

    return octalNumber;
}
Output
Enter a binary number: 101001
101001 in binary = 51 in octal

Example 2: Program to Convert Octal to Binary

In this program, the octal number to decimal to decimal at first. Then, the decimal number is converted to binary number.
#include <stdio.h>
#include <math.h>

long long convertOctalToBinary(int octalNumber);
int main()
{
    int octalNumber;

    printf("Enter an octal number: ");
    scanf("%d", &octalNumber);

    printf("%d in octal = %lld in binary", octalNumber, convertOctalToBinary(octalNumber));

    return 0;
}

long long convertOctalToBinary(int octalNumber)
{
    int decimalNumber = 0, i = 0;
    long long binaryNumber = 0;

    while(octalNumber != 0)
    {
        decimalNumber += (octalNumber%10) * pow(8,i);
        ++i;
        octalNumber/=10;
    }

    i = 1;

    while (decimalNumber != 0)
    {
        binaryNumber += (decimalNumber % 2) * i;
        decimalNumber /= 2;
        i *= 10;
    }

    return binaryNumber;
}
Output
Enter an octal number: 67
67 in octal = 110111 in binary

Comments

Popular

C Programming Enumeration

C switch...case Statement

List of all Keywords in C Language

C Programming Structure

While and Do...While Loop

C Preprocessor and Macros

C Operators