16进制字符串转数值的程序,共享一下。
VC里面没有相关的函数,近来要用,找了一下,有篇文章挺不错的,共享一下:
第一个版本,算是很常见的一个了。
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;
}
第二个版本,比较有意思吧!
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;
}
第三个和第四个基本差不多,都属于库函数的调用。
long atox(char *s)
{
long n = 0L;
sscanf(s,"%x",&n);
return n;
}
long atox(char *s)
{
return strtol(s,NULL,16);
}
总体上来说,我比较喜欢第二个。
网友 netex 看了后说:
第二个版本效率太低了。写个效率高的:
typedef unsigned int UINT;
typedef unsigned char UCHAR;
static UCHAR a2xtable[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
UINT atox(const char* s)
{
UINT res = 0;
while (*s)
{
res = (res << 4) | a2xtable[*s++];
}
return res;
}