现在的位置: 首页 > 综合 > 正文

16进制转换成10进制

2013年10月14日 ⁄ 综合 ⁄ 共 1221字 ⁄ 字号 评论关闭

#include <stdio.h>
#include <ctype.h>
#define LEN (sizeof(int)*2+3)

int htoi(const char s[]);
static int hex_int(const int c);
int htoi_zw(const char *s);

int main(void)
{
    char hex[LEN];
    while(8)
    {
        printf("请输入16进制数:");
        rewind(stdin);
        if(fgets(hex,LEN,stdin)==NULL)
            continue;
        printf("十进制值为:%u/n",htoi_zw(hex));
    }
    return 0;
}
int htoi_zw(const char *s)
{
    int n=0,yes;
      if(*s=='/0')
    return 0;
  for(;isspace(*s);s++);
  if(*s == '0')
  {
    if(*++s == 'x' || *s == 'X')
    {
      s++;
    }
  }
  for(yes=1;yes!=0;s++)
  {
      if(isdigit(*s))
        n=n*16+(*s)-'0';
      else if(*s>='a' && *s<='f')
        n=n*16+(*s)-'a'+10;
      else if(*s>='A' && *s<='F')
        n=n*16+(*s)-'A'+10;
      else yes=0;
  }
  return n;
}

int htoi(const char s[])
{
  int n = 0;
  /*if(*s=='/0')
    return 0;*/
  for(;isspace(*s);s++);
  if(*s == '0')
  {
    if(*++s == 'x' || *s == 'X')
    {
      s++;
    }
  }
  while(isdigit(*s)||hex_int(*s))
  {
      if(isdigit(*s))
        n=n*16+(*s++)-'0';
      else
        n=n*16+hex_int(*s++);
  }
  return n;
}
static int hex_int(const int c)
{
    /*if(c>'f'||c<'A'||(c>='G'&&c<'a'))
        return 0;*/
    char hex[] = "aAbBcCdDeEfF";
    int i;
    int answer = 0;
    for(i = 0; answer == 0 && hex[i] != '/0'; i++)
    {
        if(hex[i] == c)
        {
            answer = 10 + (i / 2);
        }
    }
    return answer;
}

抱歉!评论已关闭.