Converting Octal Numbers to Binary Numbers and Vice Versa in C++

Exercise:

Write a C++ program that converts octal numbers to binary numbers and binary numbers to octal numbers.

Program 1: Binary Number to Octal Number:

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int BinaryToOctal(long long);
int main()
{
    long long num;
    cout << "Insert any binary number to be converted: ";  
    cin >> num;
    cout << num << " is " << BinaryToOctal(num) << " in Octal ";
    return 0;
}
int BinaryToOctal(long long num)
{
    int ans = 0, n = 0, x = 0;
    while(num != 0)
    {
        n += (num%10) * pow(2,x);
        ++x;
        num/=10;
    }
    x = 1;
    while (n != 0)
    {
        ans += (n % 8) * x;
        n /= 8;
        x *= 10;
    }
    return ans;
}
Click Here to View the Output:
Insert any binary number to be converted: 101001110
101001110 is 516 in Octal
Click Here to View the Explanation:
  • A function is created to convert binary numbers to octal numbers.
  • The user is requested to enter a number that has to be converted. It is passed to the BinaryToOctal function.
  • The value of n is set equal to 0 and then updated by n = n%10 * pow(2,x).
  • The value of x is incremented by 1 through every iteration. if the value of n is not equal to 0, value of ans, n and x is updated.
  • The function is called in the main () function above and ans is displayed on the screen.

Program 2: Octal Number to Binary Number

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
long long OctalToBinary(int);
int main()
{
    int num;
    cout << "Insert any octal number to be converted: ";   
    cin >> num;
    cout << num << " is " << OctalToBinary(num) << " in Binary";
    return 0;
}
long long OctalToBinary(int num)
{
    int n = 0, x = 0;
    long long ans = 0;
    while(num != 0)
    {
        n += (num%10) * pow(8,x);
        ++x;
        num/=10;
    }
    x = 1;
    while (n != 0)
    {
        ans += (n % 2) * x;
        n /= 2;
        x *= 10;
    }
    return ans;
}
Click Here to View the Output:
Insert any octal number to be converted: 516
516 is 101001110 in Binary
Click Here to View the Explanation:
  • User is asked to enter the octal number to be converted to binary. The number is stored as num and passed to the OctalToBinary function.
  • Two while loops are added for the conversion in the function.
  • The first while loop updates the value of num and increments x by 1.
  • The second while loop updates the value of ans, n, and x.
  • ans is returned to the main () function. Result is displayed on the screen.

%d bloggers like this: