/*This program provides the conversion among any kinds of systems including BIN,OCT,DEC and HEX.
Input the original system, original number and destination system, then the answer will be displayed below.*/
#include <stdio.h>
int Result[100];
int OriginalNumber;
int OriginalSystem;
int DestinationSystem;
int DecToDes(int,int []);
int OriToDec(int[]);
int power(int,int);
int main(int argc, char const *argv[])
{
int i,decnum;
char temp1 [100];
int temp3 [100];
while (1)
{
a: printf("Please input the original system:");
scanf("%d",&OriginalSystem);
printf("Please input the destination system:");
scanf("%d",&DestinationSystem);
printf("Please input the original number:");
if(OriginalSystem == 16)
{
scanf("%s",temp1);
for (i = 0;temp1[i] != '\0';i++)
{
switch(temp1[i])
{
case ('A'):
case ('a'):
temp3[i] = 10;
break;
case ('B'):
case ('b'):
temp3[i] = 11;
break;
case ('C'):
case ('c'):
temp3[i] = 12;
break;
case ('D'):
case ('d'):
temp3[i] = 13;
break;
case ('E'):
case ('e'):
temp3[i] = 14;
break;
case ('F'):
case ('f'):
temp3[i] = 15;
break;
default:
temp3[i] = temp1[i]- '0';
break;
}
}
temp3[i] = -1;
}
else
{
scanf("%s",temp1);
for (i = 0;temp1[i] != '\0';i++)
temp3 [i] = temp1 [i] - '0';
temp3[i] = -1;
i--;
while(i >= 0 && temp3[i] < OriginalSystem)
i--;
if (i >= 0)
{
printf("Input error,please input again!\n");
goto a;
}
}
decnum = OriToDec(temp3);
i = DecToDes(decnum,Result);
printf("The %d form of %s is %s, the %d form is ",OriginalSystem,temp1,temp1,DestinationSystem);
if (DestinationSystem == 16)
{
printf("0x");
for(;i >= 0;i--)
{
switch (Result[i])
{
case 10:
putchar('A');
break;
case 11:
putchar('B');
break;
case 12:
putchar('C');
break;
case 13:
putchar('D');
break;
case 14:
putchar('E');
break;
case 15:
putchar('F');
break;
default:
printf("%d",Result[i]);
}
}
}
else
{
for(;i >= 0;i--)
printf("%d",Result[i]);
}
putchar('\n');
}
return 0;
}
int OriToDec(int ori[]) //Convert the input number to decimal format
{
char i,j;
int dec = 0;
for(i = 0;ori[i] != -1;i++);
for(j = 0,i--;i >= 0;i--,j++)
dec += ori[i]*power(OriginalSystem,j);
return dec;
}
int DecToDes(int dec,int res[]) //Convert the decimal format to destination system
{
int i;
for(i = 0;dec != 0;i++)
{
res[i] = dec % DestinationSystem;
dec = dec / DestinationSystem;
}
return i-1;
}
int power(int base,int times) //Calculate base^times
{
int i,result = 1;
for(i = times;i > 0;i--)
result = result*base;
return result;
}
简易进制转换器
最新推荐文章于 2022-06-28 16:47:35 发布