Friday, 20 June 2014

C++ program to convert binary to octal

Here is a C++ program to convert binary to octal. Here are the different methods to convert binary to octal like using recursion.
How to convert binary to octal (base 2 to base 8).
To convert binary to octal just take three bits and convert it in decimal number .For example let us convert binary number (101011)2 to octal.
(011)2 decimal equivalent is 3
(101)2 decimal equivalent is 5
Thus octal equivalent of binary number (101011)2 is (53)8.


Method 1 : C++ program to convert binary to octal
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    long octal=0,rem,num,temp=1,z=0;
    cout<<"Enter the number in binary ";
    cin>>num;
    while(num>0)
    {
        for(int y=0;y<3;y++)
        {
             rem=num%10;
             num/=10;
             octal+=rem*pow(2,y);
       }
       z+=octal*temp;
       octal=0;
       temp*=10;
    }
    cout<<"Octal equivalent "<<z;
    return 0;
}



Method 2 : C++ program to convert binary to octal using recursion
#include<iostream>
#include<math.h>
using namespace std;
int deci(int n,int i)
{
    if(n==0)
        return 0;
    return (n%10)*pow(2,i)+deci(n/10,i+1);
}
void octal(int n)
{
    if(n==0)
        return;
    octal(n/1000);
    cout<<deci(n%1000,0);
}
int main()
{
    int num;
    cout<<"Enter Binary number : ";
    cin>>num;
    cout<<"Octal equivalent : ";
    octal(num);
    return 0;
}



Method 3 : C++ program to convert binary to octal using function
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
void octal(int num)
{
    int octal=0,rem,temp=1,z=0;
    while(num>0)
    {
        for(int y=0;y<3;y++)
        {
             rem=num%10;
             num/=10;
             octal+=rem*pow(2,y);
       }
       z+=octal*temp;
       octal=0;
       temp*=10;
    }
    cout<<"Octal equivalent "<<z;
}
int main()
{
    int num;
    cout<<"Enter the number in binary ";
    cin>>num;
    octal(num);
    return 0;
}


Method 4 : C++ program to convert binary to octal and store it as string
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
    char bin[30],octal[10];
    int i=0,z=0,y=0,temp=0;
    cout<<"Enter the number in binary ";
    cin>>bin;
    z=strlen(bin)-1;
    while(z>=0)
    {
        for(y=0;y<3&&z>=0;y++)
             temp+=(bin[z--]-48)*pow(2,y);
        octal[i++]=temp+48;
        temp=0;
    }
    octal[i]='\0';
    strrev(octal);
    cout<<"Octal equivalent "<<octal;
    return 0;
}



No comments:

Post a Comment