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); } }