_tcstol 字符串到数字的转化



先看MSDN上对_tcstol的解释

1、在不同平台上的不同形式

TCHAR.H Routine _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined
_tcstol strtol strtol wcstol
2、定义

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

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

释义:将字符串类型根据不同的基转化数字形式。

其中:[in]   nptr 表示要进行扫描字符串指针

           [out] endptr  存储扫描后无法转化的剩余的字符串

          [base]  表示数字的基,取值为:2,8,10,16  对应的进制你懂的

这里我引用PHP中字符串匹配法则中的一个:贪婪匹配!!!也就是说,该函数会最大程序地匹配所有满足当前进制的字符,将其转化为对应的数字!!

例子:

[cpp]   view plain  copy
  1. (1).转二进制  
  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表示二进制  
  11. printf("%d\n",last);//使用十进制输出结果为1  
  12. printf("%s\n",pstr);//输出:31  
  13.  }  
讲解:上面的字符串是0131a,进行最大匹配时,只能匹配到01,当遇到3时,就会停止了,因为3不是二进制数,所以匹配后二进制数值是:01,输出为十进制为1;

再来一个例子吧

[cpp]   view plain  copy
  1. 2).转八进制  
  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表示8进制printf("%d\n",last);//使用十进制输出结果为8  
  11.   
  12.   
  13. printf("%s\n",pstr);//输出:a,!  
  14.  }  
讲解:同样,最大匹配时遇到a就走不动了,因为a不是八进制数中一个,所以最终的八进制结果为010,对应十进制数为:8

参考文章:http://fpcfjf.blog.163.com/blog/static/55469793201015111136406/

猜你喜欢

转载自blog.csdn.net/dqxiaoxiao/article/details/64423616