分享

把十六进制字符串转换为数字的几个C语言版本——文档——图形图像网

 accesine 2005-10-12

把十六进制字符串转换为数字的几个C语言版本


第一个版本,算是很常见的一个了。

#include 
#include 

long atox(char *s)
{
  long sum;

  assert(s);

  /* Skip whitespace */
  while (isspace(*s)) ++s;

  /* Do the conversion */
  for (sum = 0L; isxdigit(*s); ++s)
  {
    int digit;
    if (isdigit(*s))
      digit = *s - ‘0‘;
    else
      digit = toupper(*s) - ‘A‘ + 10;
    sum = sum*16L + digit;
  }

  return sum;
}

第二个版本,比较有意思吧!

#include 
#include 
#include 

long atox(char *s)
{
  char xdigs[] = "0123456789ABCDEF";
  long sum;

  assert(s);

  /* Skip whitespace */
  while (isspace(*s)) ++s;

  /* Do the conversion */
  for (sum = 0L; isxdigit(*s); ++s)
  {
    int digit = strchr(xdigs,toupper(*s)) - xdigs;
    sum = sum*16L + digit;
  }

  return sum;
}

第三个和第四个基本差不多,都属于库函数的调用。

#include 

long atox(char *s)
{
  long n = 0L;
  sscanf(s,"%x",&n);
  return n;
}

#include 

long atox(char *s)
{
  return strtol(s,NULL,16);
}

总体上来说,我比较喜欢第二个。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多