从字符串转数字

以下是字符串转换为数字的C代码:

unsigned __int64 StrToNum(char* _strIn)

{    

       int loop = 0;

       int base = 0;                    //代表进制

       unsigned __int64 _retNum = 0; 

       bool isHEX = false;

       char *temp = _strIn;

 

       if (_strIn[0] == '0' && (_strIn[1] == 'x' || _strIn[1] == 'X'))    //如果前缀直接是“0x”或“0X”,那么此数值是16进制

       {

              base = 16;

              _strIn += 2;

       }    

       else

       {

              while (*temp)

              {

                     if ((*temp >= 'a' && *_strIn <= 'f') || (*temp >= 'A' &&  *temp <= 'F'))    //如果字符串中包含‘a - f’或者‘A - F’,说明此数值也是16进制

                     {

                            base = 16;

                            isHEX = true;

                            break;

                     }                                              

                     temp++;

              }

 

              if (isHEX)

              {

                     base = 16;

              }

              else

                     base = 10;

       }

 

       for (loop = 0; loop < strlen(_strIn); loop++)

       {

              if(base == 10)

              {                  

                     _retNum =_retNum * 10 + ( _strIn[loop] - 0x30);                            

              }

              else if(base == 16)

              {

                     if(_strIn[loop] >= 'a' &&  _strIn[loop] <= 'f')

                     {

                            _retNum  = _retNum  * 16 + _strIn[loop] + 10 - 0x61;

                     }

                     else if(_strIn[loop] >= 'A' &&  _strIn[loop] <= 'F')

                     {

                            _retNum =_retNum  * 16  +  _strIn[loop] + 10 - 0x41;

                     }

                     else if(_strIn[loop] >= '0' &&  _strIn[loop] <= '9')

                     {

                            _retNum  = _retNum  * 16  +  _strIn[loop] - 0x30;

                     }

              }

       }

       return _retNum;

}

 

你可能感兴趣的:(从字符串转数字)