实例三十一:进制转换
问题描述:
将一个十六进制数转换为相应的十进制数输出。
Converts a hexadecimal number to the corresponding decimal number output.
算法思路:
- 十六进制某些数位不属于十进制整型数据,所以为了便于取出十六进制数的每个位数,应用字符串来表示一个十六进制数。
Some digits in hexadecimal are not decimal integer data, so in order to easily take out each digit of a hexadecimal number, a string is used to represent a hexadecimal number. - 把十六进制数转换为十进制数,首先要把字符串转换为十进制数,且这个字符串必须是 0~9 与 a~f(或 A~F)这些字符组成的,因此,输入一个十六进制数时必须根据这个约束条件进行识别判断字符串(十六进制数)是否合法。
To convert a hexadecimal number to a decimal number, first convert the string to a decimal number, and the string must be 0~9 and a~f (or A~F). Therefore, enter a ten. When the hexadecimal number is used, it is necessary to identify whether the character string (hexadecimal number) is legal according to this constraint.
#include <stdio.h>
#define MAX 100
int main(void)
{
int htoi(char s[]);
char t[MAX], c;
int i=0,flag=0,flag1=1;
printf("\nInput a hex number:");
while((c=getchar())!='0'&&i<MAX&&flag1)
{
if((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F'))
{
flag=1;
t[i++]=c;
}
else if(flag)
{
t[i]='\0';
printf("decimal number is %d\n",htoi(t));
printf("continue or not?");
c=getchar();
if(c=='N'||c=='n')
flag1=0;
else
{
flag=0;
i=0;
printf("\nInput aa hex number:");
}
}
}
return 0;
}
int htoi(char s[])
{
int i,n=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='0'&&s[i]<='9')
n=n*16+s[i]-'0';
if(s[i]>='a'&&s[i]<='f')
n=n*16+s[i]-'a'+10;
if(s[i]>'A'&&s[i]<='F')
n=n*16+s[i]-'A'+10;
}
return 0;
}