前文:
C语言char数组/uint8_t数组转float类型,可用于单片机
再提供一个float转char数组的,因为用sprintf的话在stm32c8t6里容易卡死,不知道什么原因,所以手撸了一个
//float转char数组,一次转一个
void float2char(float value/*需要转换的值*/,
char* cSendBuff/*结果存储的数组*/, int Decimals/*小数位的长度*/)
int i = 1, k = 0;
int integer = abs(value);//整数部分
int decimal = (abs(value) - integer)*pow(10, Decimals);//小数部分
int temp = integer;
if (value < 0)cSendBuff[k++] = '-';//如果小于0,加个负号
while (temp /= 10)
{
i*=10;
}
while (integer) {
cSendBuff[k++] = integer / i + '0';
integer %= i;
i /= 10;
}
if (Decimals == 0) { //如果没有小数位,直接返回
cSendBuff[k++] = '\0';
return;
}
cSendBuff[k++] = '.'; //加小数点
temp = decimal;
i = 1;
while (temp /= 10)
{
i *= 10;
}
while (decimal) {
cSendBuff[k++] = decimal / i + '0';
decimal %= i;
i /= 10;
}
cSendBuff[k++] = '\0';
}
使用例程:
float value = 12562.1542;
char a[50] = { 0 };
float2char(value, a, 4);
cout << "译码结果:" << a << endl;
接下来如果需要把单个的字符串连接成长的字符串,可以调用strcat()。
这篇博客介绍了如何在C语言环境下,特别是在STM32单片机中,将float类型数值转换为char数组的方法。由于使用sprintf函数可能导致卡死,作者提供了一个手动实现的float到char数组的转换函数。该函数考虑了正负数、整数和小数部分的处理,并给出了使用示例。此外,还提到了字符串连接的方法以及在单片机环境中可能遇到的问题。
504

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



