前文:
qC语言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 = value;//整数部分
int decimal = (value - integer)*pow(10, Decimals);//小数部分
int temp = integer;
while (temp /= 10)
{
i*=10;
}
while (integer) {
cSendBuff[k++] = integer / i + '0';
integer %= i;
i /= 10;
}
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;