用c语言编写函数Htoi(s)把16进制数转成10进制的数

http://zhidao.baidu.com/question/24901138.html

用c语言编写函数Htoi(s)把由16进制数字组成的字符串 转化成与之等价的整型值,字符串中允许包含0-9,a-f,A-F.

 

#include "stdio.h"
#include "string.h"
int translat(char c)
{
if(c<='9'&&c>='0') return c-'0';
if(c>='a' && c<='f') return c-87;
if(c>='A' && c<='F') return c-55;
return -1;//其它字符返回-1
}

int Htoi(char *str)
{
int length=strlen(str);
if(length==0) return 0;
int i,n=0,stat;
for(i=0;i<length;i++)
{
  stat=translat(str[i]);//防错处理
  if(stat>=0) n=n*16+stat;
}
return n;
}
void main()
{
char Hex[20];
printf("Input Num at Hexadecimal:");
gets(Hex);
printf("%s=%d",Hex,Htoi(Hex));
}

posted @ 2010-08-27 16:50  牧羊的小牧童  阅读(7592)  评论(0编辑  收藏  举报