Friday, 20 June 2014

C++ program to convert octal to hexadecimal number

Here is a C++ program to convert octal to hexadecimal.
How to convert octal to hexadecimal (base 8 to base 16).
At first convert each digit in octal to binary and than convert binary to hexadecimal. For example convert (74)8 to hexadecimal.
(74)8 = (111100)2
(111100)2 = (3C)16
(74)8 = .(3C)16

Method 1 : C++ to convert octal to hexadecimal
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    long z=1,i,temp,binary=0,hexa[20],rem,num;
    for(i=0;i<20;i++)
        hexa[i]=0;
    cout<<"Enter the number in octal ";
    cin>>num;
    cout<<"Hexadecimal equivalent : ";
    /* Convertirng octal to binary*/
    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;
        }
    }
    /*Comverting Binary to Hexadecimal*/
    for(i=0;binary>0;i++)
    {
        for(int y=0;y<4;y++)
        {
             rem=binary%10;
             binary/=10;
             hexa[i]+=rem*pow(2,y);
       }
    }
    while(i>0)
    {
        i--;
        if(hexa[i]>9)
            cout<<char(55+hech[i]);
        else
            cout<<hexa[i];
    }
    return 0;
}




Method 2 : C++ to convert octal to hexadecimal using recursion
#include<iostream>
#include<math.h>
using namespace std;
int bin=0;
void binary(int n,int temp,int z)
{
    if(z==3)
        return ;
    bin+=(n%2)*temp;
    binary(n/2,temp*10,z+1);
}
void octal(int n,int j)
{
    if(n==0)
        return;
    octal(n/10,j*1000);
    binary(n%10,j,0);
}
int deci(int n,int i)
{
    if(n==0)
        return 0;
    return (n%10)*pow(2,i)+deci(n/10,i+1);
}
void hex(int n)
{
    int hexa;
    if(n==0)
        return;
    hex(n/10000);
    hexa=deci(n%10000,0);
    if(hexa>9)
        cout<<char(55+hexa);
    else
        cout<<hexa;
}
int main()
{
    int num;
    cout<<"Enter Octal number : ";
    cin>>num;
    cout<<"Hexadecimal equivalent : ";
    octal(num,1);
    hex(bin);
    return 0;
}

No comments:

Post a Comment