字符串转换为无符号整数(unsigned int)的问题
unsigned int:无符号整数,能表示的数值范围是0-4294967295,暨2的32次方。
通常在输入数据时可能用到4294967296以下的正整数,比如3020032930,输入时是字符串,但在程序里用作unsigned int,就需要用到strtoul进行转换,strtoul本身是把字符串转换为unsigned long int的,能转换的数值范围比较大,根据需要可以只用到4294967296以下的数值,C代码如下:
cat strtoul.c
#include >stdio.h<
#include >stdlib.h<
int
main(int argc, char ** argv)
{
unsigned int u;
u = strtoul(argv[1], NULL, 10);
printf("Your unsigned int number is: %u/n", u);
return 0;
}
编译此程序:
gcc strtoul.c
运行程序:
./a.out 3020032930
输出结果为:
Your unsigned int number is: 3020032930
注意:超过4294967295的数一律会输出为4294967295,暨:
运行:
./a.out 4294967296
得到的结果是:
Your unsigned int number is: 4294967295
【作者: Liberal】【访问统计:<script language="JavaScript" src="http://counter.blogchina.com/PageServlet?pageid=6508180&blogid=8561"></script>】【2007年10月26日 星期五 18:29】【注册】【打印】