_tcstol string to number conversion



First look at the explanation of _tcstol on MSDN

1. Different forms on different platforms

TCHAR.H Routine _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined
_tcstol strtol strtol wcstol
2. Definition

long strtol( const char *nptr, char **endptr, intbase);

long wcstol( const wchar_t *nptr, wchar_t **endptr, intbase);

Definition: Convert a string type into a numeric form according to different bases.

Among them: [in]    nptr  indicates the string pointer to be scanned

           [out] endptr stores the remaining strings that cannot be converted after scanning

          [ base ] Indicates the base of the number, the value is: 2, 8, 10, 16. You know the corresponding base

Here I quote one of the rules of string matching in PHP : greedy matching! ! ! That is to say, this function will programmatically match all characters that satisfy the current base and convert them into corresponding numbers ! !

example:

[cpp]   view plain  copy
  1. (1). Convert to binary  
  2.   
  3. #include"afx.h"  
  4. #include<stdio.h>  
  5. void main()  
  6. {  
  7. char c[5]="0131";  
  8. CString cs=_T(c);  
  9. LPTSTR pstr  = NULL;  
  10. int  last=_tcstol(c,pstr,2); //2 means binary  
  11. printf( "%d\n" ,last); //Use decimal to output the result as 1  
  12. printf( "%s\n" ,pstr); //Output: 31  
  13.  }  
Explanation: The above string is 0131a. When the maximum match is performed, it can only match to 01. When it encounters 3, it will stop. Because 3 is not a binary number, the binary value after matching is: 01, and the output is in decimal as 1;

Let's take another example

[cpp]   view plain  copy
  1. 2). Convert to octal  
  2.   
  3. #include"afx.h"  
  4. #include<stdio.h>  
  5. void main()  
  6. {  
  7. char c[7]="010a,!";  
  8. CString cs=_T(c);  
  9. LPTSTR pstr  = NULL;  
  10. int  last=_tcstol(c,pstr ,8); //8 means octal printf("%d\n",last);//The output result in decimal is 8  
  11.   
  12.   
  13. printf( "%s\n" ,pstr); //Output: a,!  
  14.  }  
Explanation: Similarly, when encountering a at the maximum match, it cannot move, because a is not one of the octal numbers, so the final octal result is 010, and the corresponding decimal number is: 8

Reference article: http://fpcfjf.blog.163.com/blog/static/55469793201015111136406/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325989154&siteId=291194637