Home »
C++ Programs
C++ program to convert octal number to binary number using class
Submitted by Shubh Pachori, on August 08, 2022
Problem statement
Given an octal number, we have to convert it to binary number using the class and object approach.
Example:
Input:
Enter Octal Number: 25
Output:
Binary Digit: 10101
C++ code to convert octal number to binary number using class and object approach
#include <iostream>
#include <cmath>
using namespace std;
// create a class
class OctalToBinary {
// private data member
private:
int octal;
// public functions
public:
// getOctal() function to get Octal Number
void getOctal() {
cout << "Enter Octal Number:";
cin >> octal;
}
// OToB() function to convert octal to binary
long long OToB() {
// initialising variables to perform operations
int decimal = 0, index = 0;
long long binary = 0;
// while loop to convert octal to decimal
while (octal != 0) {
decimal = decimal + (octal % 10) * pow(8, index);
index++;
octal = octal / 10;
}
index = 1;
// while loop to convert decimal to binary
while (decimal != 0) {
binary = binary + (decimal % 2) * index;
decimal = decimal / 2;
index = index * 10;
}
// returning binary digit
return binary;
}
};
int main() {
// create a object
OctalToBinary O;
// initialize a int type variable to store the value
int b;
// calling getOctal() function to insert the Octal Number
O.getOctal();
// calling OToB() function to convert it
b = O.OToB();
cout << "Binary Digit:" << b;
return 0;
}
Output
Enter Octal Number:31
Binary Digit:11001
Explanation
In the above code, we have created a class OctalToBinary, one int type data member octal to store the octal number, and public member functions getOctal() and OToB() to store and convert the given octal number to a binary digit number.
In the main() function, we are creating an object O of class OctalToBinary, reading the octal number given by the user using getOctal() function, and finally calling the OToB() member function to convert the given octal number. The OToB() function contains the logic to convert the given octal number to binary number and printing the result.
C++ Class and Object Programs (Set 2) »