gpt4 book ai didi

不使用 sprintf() 将 float 转换为字符串

转载 作者:行者123 更新时间:2023-11-30 16:57:44 25 4
gpt4 key购买 nike

我正在为基于微 Controller 的应用程序进行编码,我需要将浮点转换为字符串,但我不需要与 sprintf() 相关的繁重开销。有什么 Eloquent 方法可以做到这一点吗?我不需要太多。我只需要 2 位精度。

最佳答案

这是一个针对嵌入式系统优化的版本,不需要任何 stdio 或 memset,并且内存占用很小。您负责传递一个用零初始化的字符缓冲区(带有指针p),您要在其中存储字符串,并在创建所述缓冲区时定义CHAR_BUFF_SIZE(因此返回的字符串将以 null 结尾)。

static char * _float_to_char(float x, char *p) {
char *s = p + CHAR_BUFF_SIZE; // go to end of buffer
uint16_t decimals; // variable to store the decimals
int units; // variable to store the units (part to left of decimal place)
if (x < 0) { // take care of negative numbers
decimals = (int)(x * -100) % 100; // make 1000 for 3 decimals etc.
units = (int)(-1 * x);
} else { // positive numbers
decimals = (int)(x * 100) % 100;
units = (int)x;
}

*--s = (decimals % 10) + '0';
decimals /= 10; // repeat for as many decimal places as you need
*--s = (decimals % 10) + '0';
*--s = '.';

while (units > 0) {
*--s = (units % 10) + '0';
units /= 10;
}
if (x < 0) *--s = '-'; // unary minus sign for negative numbers
return s;
}

在 ARM Cortex M0 和 M4 上测试。正确舍入。

关于不使用 sprintf() 将 float 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39366288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com