整型与字符串互转

来源:互联网 发布:网络推广网站有哪些 编辑:程序博客网 时间:2024/06/05 14:08

    今天要用到将整形数据转成字符串,或是将字符串转成整型,直接想到了用atoi和itoa函数来做转换,但是在编译的时候编不过,因为不识别这两个函数,可能是因为这两个函数不是标准的C函数;

     然后想到用sprintf将整形数据转成字符串;

                    用sscanf函数将字符串转成整形数据;

还有一个strtol函数也可以将字符串转成整形数据;


sprintf解析实例:

char test_string[4096] = {0};

int a = 243;
sprintf(test_string, "%d", a);
printf("test_string=[%c][%c][%c]\n", test_string[0],test_string[1], test_string[2] );


执行结果:

test_string=[2][4][3]


解析字符串常用函数:

strstr:在一个字符串中查找另一个字符串,没找到时返回NULL;

strcmp:比较两个字符串,相等时返回0;

strcasecmp:

表头文件 #include <strings.h>(不是C/C++的标准头文件,区别于string.h[1] )
定义函数 int strcasecmp (const char *s1, const char *s2);
函数说明 strcasecmp()用来比较参数s1和s2字符串,比较时会自动忽略大小写的差异。
返回值 若参数s1和s2字符串相等则返回0。s1大于s2则返回大于0 的值,s1 小于s2 则返回小于0的值

整型转整型转字符串:
root@netcore:/usr/bin# 
root@netcore:/usr/bin# cat /sys/devices/platform/mv_pon/info/parameter
Module support:          yes
TX optical power(0.1uW): 16221
RX optical power(0.1uW): 1483
TCverTemperature(1/256): 9485
SupplyVoltage(100uV):    33792
BiasCurrent(2uA):        5375
上面是设备上的PON的参数:
电压的转换:
char in_ptr[16] = {33792};
int Vottage = 0;
float tmp;

sscanf(in_ptr, "%d", &Vottage);
       tmp = Vottage/10000.0;       //将整型转float;      
       sprintf(pstatus->ucVottage,"%0.2fV",tmp);     //将float转字符串,取小数点后两位;

0 0