Program to Convert between Bin,Oct,Dec and Hex form
#include < stdio.h>
#include < conio.h>
#include < string.h>
int conv(char c);
tobin(int a);
tooct(int b);
tohex(int a);
main()
{
int l,m,k,i,j,a;
char n[25];
clrscr();
printf("Enter the no followed by type(as 1001b,234d,654o,4AC6h etc) : ");
scanf("%s",n);
l=strlen(n);
switch(n[l-1])
{
case 'b':
j=2;
break;
case 'o':
j=8;
break;
case 'h':
j=16;
break;
case 'd':
j=10;
break;
default:
j=10;
l++;
break;
}
a=0;
m=1;
for(i=l-2;i>=0;i--)
{
k=conv(n[i]);
a=a+k*m;
m=m*j;
}
printf("\n\n Dec : %d",a);
tobin(a);
tooct(a);
tohex(a);
getch();
}
int conv(char a)
{
int p;
p=char(a);
if(p>47)
return(p-48);
else if(p>64)
return(p-55);
else if(p>96)
return(p-97);
}
tobin(int a)
{
char h[300];
int l,i,k;
for(i=0;a!=0;i++)
{
k=a%2;
h[i]=char(48+k);
a=a/2;
}
l=i-1;
printf("\n\n Bin : ");
for(i=l;i>=0;i--)
printf("%c",h[i]);
}
tooct(int a)
{
int b=0,k,m=1;
while(a!=0)
{
k=a%8;
b=b+m*k;
m=m*10;
a=a/8;
}
printf("\n\n Oct : %d",b);
}
tohex(int a)
{
char h[30];
int l,i,k;
for(i=0;a!=0;i++)
{
k=a%16;
if(k < 10)
h[i]=char(48+k);
else
h[i]=char(55+k);
a=a/16;
}
l=i-1;
printf("\n\n Hex : ");
for(i=l;i>=0;i--)
printf("%c",h[i]);
}
0 comments:
Post a Comment