单片机浮点数转字符串可以使用 stdio.h 中sprintf函数,但代码体积和RAM占用空间比较大。自己写的程序又不太好。在学习GPS数据解析过程中用到了LeiOuYang的GPS解析库,在其中有浮点数转字符串函数,现推荐给大家。
一下是完整的基于KEIL C51 的C文件:
//#include <string.h>
//#include <stdio.h> //使用sprintf时取消该注释
#define DIGITAL_TO_CHAR(x) ( (x)+'0' )
unsigned char DispBuff[5];
/* 多次方 */
static int int_pow(int value, unsigned int count)
{
int v = 1;
while(count--)
v = v*value;
return v;
}
/* 浮点数转换为字符串,包括整数转换为字符串
* intgr指定整数位个数,dec指定小数位个数
* 自动去除前面的0,小数点后面的0不会舍去
*/
static unsigned char float_to_string(double value, char* pdest, unsigned int intgr, unsigned int dec)
{
char* pstr = (void*)0;
double fvalue = 0.0;
char c = 0;
unsigned int tvalue = 0;
unsigned char zeroflag = 0;
unsigned int tm = 0;
if( (void*)0==pdest || 0==intgr ) return 0;
if(dec>9) dec = 9;
if(1==intgr) zeroflag = 1;
pstr = pdest;
if(value<-0.000000000000000001)
{
*pstr = '-';

本文介绍了一种在单片机环境下优化的浮点数到字符串转换方法,相较于使用stdio.h中的sprintf函数,该方法能有效减少代码体积和RAM占用。通过具体代码示例,展示了如何实现这一转换过程,并比较了与sprintf函数的不同。
最低0.47元/天 解锁文章
7616

被折叠的 条评论
为什么被折叠?



