static int _atoul(const char *str, unsigned char *pvalue)
{
unsigned int result=0;
while (*str)
{
if (isdigit((int)*str))
{
//对于unsigned int为32位的编译环境来说,result最大的值为4294967296
if ((result<429496729) || ((result==429496729) && (*str<'6')))
{
//'0'的ASCII码为48
result = result*10 + (*str)-48;
}
else
{
*pvalue = result;
return -1;
}
}
else
{
*pvalue=result;
return -1;
}
str++;
}
*pvalue=result;
return 0;
}
#define ASC2NUM(ch) (ch - '0')
#define HEXASC2NUM(ch) (ch - 'A' + 10)
static int _atoulx(const char *str, unsigned char *pvalue)
{
unsigned int result=0;
unsigned char ch;
while (*str)
{
ch=toupper(*str);//字符串转为大写表示
if (isdigit(ch) || ((ch >= 'A') && (ch <= 'F' )))
{
//对于unsigned int为32位的编译环境来说,result最大的值为4294967296,十六进制表示为0x10000000
if (result < 0x10000000)
{
result = (result << 4) + ((ch<='9')?(ASC2NUM(ch)):(HEXASC2NUM(ch)));
}
else
{
*pvalue=result;
return -1;
}
}
else
{
*pvalue=result;
return -1;
}
str++;
}
*pvalue=result;
return 0;
}
/*used for convert hex value from string to int*/
//第二个参数pvalue的类型为unsigned char *?为什么不是unsigned int *
static int str_to_num(const char *str, unsigned char *pvalue)
{
if ( *str == '0' && (*(str+1) == 'x' || *(str+1) == 'X') ){
if (*(str+2) == '\0'){
return -1;
}
else{
//十六进制转换
return _atoulx(str+2, pvalue);
}
}
else {
//字符串转十进制
return _atoul(str,pvalue);
}
}