其实算法很简单,如果判断字符串为一个十六进制数的字符串(通过if(strstr(str,"0x") || strstr(str,"0X"))来判断),就进行每一位的一次转换。其中需要用到pow(x,y)函数,该函数用来计算x的y次幂的值。
#include
int Str2Int(char* str)
{
if(strstr(str,"0x") || strstr(str,"0X"))
{
str += 2;
int tmp = 0;
int len = strlen(str);
int i = 0;
for(i = 0;i < len ;i++)
{
int nDecNum;
switch(str[i])
{
case 'a':
case 'A':
nDecNum = 10;
break;
case 'b':
case 'B':
nDecNum = 11;
break;
case 'c':
case 'C':
nDecNum = 12;
break;
case 'd':
case 'D':
nDecNum = 13;
break;
case 'e':
case 'E':
nDecNum = 14;
break;
case 'f':
case 'F':
nDecNum = 15;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nDecNum = str[i] - '0';
break;
default:
return 0;
}
tmp += nDecNum*pow(16,len-i-1);
}
return tmp;
}
else
{
return atoi(str);
}
}
int main()
{
char* str = "0x2a";
int i = 0;
i = Str2Int(str);
printf("%d\n", i);
return 0;
}
阅读(4869) | 评论(0) | 转发(0) |