View Single Post
Go4Expert Member
30Jun2007,15:50  
seeguna's Avatar
Supriya,
Shabbir already provide a good article for number conversion.Go thru it for all type of number conversions.
For your reference i make a slight touch to existing (Shabbir) program.
To convert Hexadecimal no to octal no......(I just combined two functions into a single one)

Coding listed below:
//first convert Hex to Dec number
//Next convert Dec to Oct number

Code: CPP
#include<stdio.h>
#include<string.h>
#include<math.h>
void main()
{
    char hex[100];
    double dec=0.0;
    int oct[100],temp[100];
    int len,i,j,num=0;
   
    printf("Enter a hexadecimal number");
    scanf("%s",hex);
    len=strlen(hex);
   
    for(i=0;i<len;i++)
    {
        switch(hex[i])
        {
        case '0':
            temp[i]=hex[i]-48;     //Ascii code of 0 is 48  48-48=0//
            break;
        case '1':
            temp[i]=hex[i]-48;    //Ascii code of 1 is 49  49-48=1//
            break;
        case '2':
            temp[i]=hex[i]-48;    //Ascii code of 2 is 50  50-48=2//
            break;
        case '3':
            temp[i]=hex[i]-48;    //Ascii code of 3 is 51  51-48=3//
            break;
        case '4':
            temp[i]=hex[i]-48;    //Ascii code of 4 is 52  52-48=4//
            break;
        case '5':
            temp[i]=hex[i]-48;    //Ascii code of 5 is 53  53-48=5//
            break;
        case '6':
            temp[i]=hex[i]-48;    //Ascii code of 6 is 54  54-48=6//
            break;
        case '7':
            temp[i]=hex[i]-48;    //Ascii code of 7 is 55  55-48=7//
            break;
        case '8':
            temp[i]=hex[i]-48;    //Ascii code of 8 is 56  56-48=8//
            break;
        case '9':
            temp[i]=hex[i]-48;    //Ascii code of 9 is 57  57-48=9//
            break;
        case 'A':
            temp[i]=hex[i]-55;     //Ascii code of A is 65 65-55=10//
            break;
        case 'B':
            temp[i]=hex[i]-55;    //Ascii code of B is 65 66-55=11//
            break;
        case 'C':
            temp[i]=hex[i]-55;    //Ascii code of C is 65 67-55=12//
            break;
        case 'D':
            temp[i]=hex[i]-55;    //Ascii code of D is 65 68-55=13//
            break;
        case 'E':
            temp[i]=hex[i]-55;    //Ascii code of E is 65 68-55=14//
            break;
        case 'F':
            temp[i]=hex[i]-55;    //Ascii code of F is 65 69-55=15//
            break;
        }
    }
    for(i=0,j=len;i<len;i++,j--)
        dec=dec+(temp[j-1]*pow(16,i));
    printf("The decimal equivalent is %lg \n",dec);
    num=(int)dec;
    //OCTAL CONVERSION
    for(i=0;num!=0;i++)
    {
        oct[i]=num%8;
        num=num/8;
    }
    i--;
    printf("\n Octal equivalent number:");
    for(;i>=0;i--)
        printf("%d",oct[i]);
    printf("\n");

}

Last edited by shabbir; 30Jun2007 at 22:22.. Reason: Code block