Friday 20 June 2014

C++ program to convert octal to binary number


Here is a C++ program to convert octal to binary. Here are the different methods to convert octal to binary like using recursion, using bitwise operator etc.
How to convert octal to binary (base 8 to base 2).
To convert octal to binary a simple just convert each digit of octal number to binary .For example let us convert octal number (65)8 to binary.
6 = (110)2
5 = (101)2
 (65)8 = (110101)2.

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



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



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



Method 4 : C++ program to convert octal to binary using bitwise operator
#include<iostream>
#include<math.h>
using namespace std;
void bin(int num)
{
    int amask,k,num1=num%10;
    if(num==0)
        return;
    bin(num/10);
    for(int i=2;i>=0;i--)
    {
        amask=1<<i;
        k=num1&amask;
        k==0?cout<<"0":cout<<"1";
    }

}
int main()
{
    int rem,num,num1,num2;
    cout<<"Enter the number in octal ";
    cin>>num;
    cout<<"Binary equivalent = ";
    bin(num);
    return 0;
}




Method 5 : C++ program to convert octal to binary and store it as string
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char a[20];
    int i=0,n,temp;
    cout<<"Octal number : ";
    cin>>n;
    while(n>0)
    {
        temp=n%10;
        n/=10;
        for(int y=0;y<3;y++)
        {
            a[i++]=temp%2+48;
            temp=temp/2;
        }
    }
    a[i]='\0';
    strrev(a);
    cout<<"Binary equivalent : "<<a;
    return 0;
}

No comments:

Post a Comment