- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Convert Octal Number to Binary Number
In a computer system, the binary number is expressed in the binary numeral system while the octal number is in the octal numeral system. The binary number is in base 2 while the octal number is in base 8.
Examples of binary numbers and their corresponding octal numbers are as follows −
Binary Number | Octal Number |
---|---|
01101 | 15 |
00101 | 5 |
10110 | 26 |
01010 | 12 |
A program that converts the octal numbers into binary is given as follows −
Example
#include <iostream> #include <cmath> using namespace std; int OctalToBinary(int octalNum) { int decimalNum = 0, binaryNum = 0, count = 0; while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,count); ++count; octalNum/=10; } count = 1; while (decimalNum != 0) { binaryNum += (decimalNum % 2) * count; decimalNum /= 2; count *= 10; } return binaryNum; } int main() { int octalNum = 33; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }
Output
The output of the above program is as follows −
Octal to Binary Octal number: 33 Binary number: 11011
In the given program, the function OctalToBinary() converts the given octal number into a binary number This is done by first converting the octal number into a decimal number and then converting the decimal number into an binary number. This is seen in the following code snippet −
int OctalToBinary(int octalNum) { int decimalNum = 0, binaryNum = 0, count = 0; while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,count); ++count; octalNum/=10; } count = 1; while (decimalNum != 0) { binaryNum += (decimalNum % 2) * count; decimalNum /= 2; count *= 10; } return binaryNum; }
In the function main(), the octal number is given. Then its corresponding binary number is calculated by calling OctalToBinary(). This is shown below −
int main() { int octalNum = 33; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }