Technorati 标签: strtol, strtoul, strtod
函数原型:
long int strtol ( const char * str, char ** endptr, int base );
unsigned long int strtoul ( const char * str, char ** endptr, int base );
double strtod ( const char * str, char ** endptr );
这几个函数从str指向的字符开始转化,忽略掉前面的空格,遇到错误无法转换的字符则返回,如果endptr不为空,则将该字符存储在endptr里。
对前两个函数,base则表示其进制。
想到之前的一篇笔记:http://www.cppblog.com/izualzhy/archive/2012/07/09/182456.html
需要将”0xE4”转到E4(1个字节)
可以简单的这么写了:
char str[] = "E4"; int a; a = strtol(str,NULL,16);
看个详细的例子:
/* * ===================================================================================== * Filename: strtodata.c * Description: string to long/unsigned long/double * * Version: 1.0 * Created: 08/16/2012 07:30:17 PM * * Author: zhy (), [email protected] * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> int main() { char numbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff"; char *pEnd; long int li1,li2,li3,li4; li1 = strtol(numbers, &pEnd, 10); li2 = strtol(pEnd, &pEnd, 16); li3 = strtol(pEnd, &pEnd, 2); li4 = strtol(pEnd, NULL, 0); printf("The decimal equivalents are: %ld, %ld, %ld, %ld.\n",li1,li2,li3,li4); char digits[] = "365.24 29.53 -1.23456"; double d1,d2,d3; d1 = strtod(digits, &pEnd); printf("%c\n", *pEnd); d2 = strtod(pEnd, &pEnd); d3 = strtod(pEnd, NULL); printf("The moon completes %f/%f orbits per Earth yes.%f\n",d1,d2,d3); return 0; }
运行结果:
The decimal equivalents are: 2001, 6340800, -3624224, 7340031.
The moon completes 365.240000/29.530000 orbits per Earth yes.-1.234560
参考资料:
http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/