ad

Tuesday, 3 January 2012

octal to hexa decimal andvice versa conversion in c

//Decimal to hexa decimal & octal
#include< stdio.h>
#include< conio.h>
#include< math.h>
#include< string.h>
#include< process.h>
float check(char *a)
{
int f=0,i,x;
float m;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='.')
f=f+1;
if(f>=2)
{
printf("\n\nInvalid entry.....");
getch();
exit(0);
}
}
for(i=0;a[i]!='\0';i++)
{
if(a[i]!='.')
{
x=isdigit(a[i]);
if(x==0)
{
printf("\n\n\t\tInvalid entry.....");
getch();
exit(0);
}
}
}
if(x!=0)
{
m=atof(a);
return(m);
}
}
void main()
{
char ch,st[12];
int O=8,H=16;
float D;
void convert(float,int);
clrscr();
printf("\n\t\t***DECIMAL TO OCTAL && HEXADECIMAL***");
do
{
printf("\n\n\n\nEnter the decimal number : ");
scanf("%s",st);
D=check(st);
printf("\n\n\tThe equivalent octal number is : ");
convert(D,O);
printf("\n\n\tThe equivalent hexadecimal number is : ");
convert(D,H);
printf("\n\n\n\t\t\tDo you want to continue?[y/n]\n");
ch=getch();
}while(ch=='y'||ch=='Y');
exit(0);
getch();
}
void convert(float d,int s)
{
char st[15];
int i,N=0,r1[50],r2[50],j;
float D,t=0,chk;
N=d;
D=d-N;
chk=D;
if(D!=0)
{
for(i=0;i<4;i++)
{
t=D*s;
r1[i]=t;
D=t-r1[i];
}
}
i=0;
while(N!=0)
{
r2[i]=N%s;
N=N/s;
i++;
}
for(j=i-1;j>=0;j--)
{
if(r2[j]<10)
printf("%d",r2[j]);
else
{
switch(r2[j])
{
case 10:printf("A");
break;
case 11:printf("B");
break;
case 12:printf("C");
break;
case 13:printf("D");
break;
case 14:printf("E");
break;
case 15:printf("F");
break;
}
}
}
if(chk!=0)
{
printf(".");
for(j=0;j<4;j++)
{
if(r1[j]<10)
printf("%d",r1[j]);
else
{
switch(r2[j])
{
case 10:printf("A");
break;
case 11:printf("B");
break;
case 12:printf("C");
break;
case 13:printf("D");
break;
case 14:printf("E");
break;
case 15:printf("F");
break;
}
}
}
}
}

No comments:

Post a Comment