#include "stdafx.h"
#include <string.h>
/*htoi: converts hexadecimal string to integer */
int htoi(char s[])
{
int hexdigit,i,n;
i = 0;
if(s[i] == '0') /*skip optional 0x or 0X*/
{
i++;
if(s[i] == 'x' || s[i] == 'X')
i++;
}
n= 0; /*integer value to be returned*/
for ( ; i < strlen(s);i++)
{
if(s[i] >= '0' && s[i] <= '9')
{
hexdigit = s[i] - '0';
}
else if (s[i] >= 'a' && s[i] <= 'f')
{
hexdigit = s[i] - 'a' + 10;
}
else if (s[i] >= 'A' && s[i] <= 'F')
{
hexdigit = s[i] - 'A' + 10;
}
else
{
return -1; /* not a valid hexadecimal digit ,and return -1*/
}
n = 16*n + hexdigit;
}
return n;
}
int _tmain(int argc, _TCHAR* argv[])
{
int integer = 0;
char hexstr[] = "0xfE3";
integer = htoi(hexstr);
if(-1 == integer)
{
printf("\r\n The hexadecimal string:%s invalid.\r\n",hexstr);
}
else
{
printf("\r\n The hexadecimal string is:%s,and convert to integer digit is:%d.\r\n",hexstr,integer);
}
return 0;
}
把由十六进制数字组成的字符串转换为与之等价的整数值
最新推荐文章于 2021-10-16 17:49:18 发布