Binary to Octal Conversion
“Binary to Octal Conversion” is one of the classic programming problem for beginners. Here, we are given a Binary Number, entered by user and our task is to write a program to convert the given binary number to its equivalent octal number.
Example (Binary to Octal Conversion):
Binary = 100011011 Octal = 433
The steps required for Binary to Octal Conversion are as follows:
- Make sure the number of digits in binary number is divisible by 3. If not, add extra 0s in front.
- Divide the binary number into pairs of 3-digit binary number.
- Convert each 3-digit binary number pair to its decimal form.
- Combine all the decimal numbers and store into ‘Octal’.
- Print the result.
C++ Program for Binary to Octal Conversion is as follows:
/* C++ Program for Binary to Octal Conversion Number*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan the Binary Number */
string Binary;
cout<<"Enter the Binary Number: ";
cin>>Binary;
/* Converting Binary to Octal*/
/* Make sure the number of digits in 'Binary'
Number is divisible by 3. If not, add
required 0s in front*/
while(Binary.length() % 3 != 0)
{
Binary.insert(0,"0");
}
/* Converting each digit of Binary number
into 3-digit binary number pair and convert
each pair to its corresponding decimal
*/
string Octal = "";
for(int i = 0; i < Binary.length(); i=i+3)
{
string temp;
temp = temp + Binary[i];
temp = temp + Binary[i+1];
temp = temp + Binary[i+2];
if(temp == "000")
Octal += '0';
else if(temp == "001")
Octal += '1';
else if(temp == "010")
Octal += '2';
else if(temp == "011")
Octal += '3';
else if(temp == "100")
Octal += '4';
else if(temp == "101")
Octal += '5';
else if(temp == "110")
Octal += '6';
else if(temp == "111")
Octal += '7';
}
/*Printing the result */
cout<<"The Octal of "<<Binary<<" is "<<Octal;
}
OUTPUT: Enter the Binary Number: 100011011 The Octal of 100011011 is 433
Related Posts:
- Program to convert binary number to decimal number.
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.
- Program to convert decimal number to binary number.
- Program to convert decimal number to octal number.
- Program to convert decimal number to hexadecimal number.
- Program to convert hexadecimal number to binary number.
- Program to convert hexadecimal number to octal number.
- Program to convert hexadecimal number to decimal number.
- Program to find sum of first ‘n’ natural numbers.
- Program to Reverse a Number.
- Program to swap two Numbers.
- Program to print Fibonacci Series up to Nth Term.
- Program to find and print nth Fibonacci number.
- Program to find Power of the Number.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.