介绍

在dsp中写一个保留2位小数的函数

1
2
3
4
5
// 保留2位小数的函数
float round_to_2_decimal(float value)
{
return (float)((int)(value * 100 + 0.5f)) / 100.0f;
}

dsp通过SCI串口传给上位机的浮点数据累加到一定程度莫名其妙的就不能增长了!

img

思考

上面的数据看上去只有2个字节,数据转换的中间环节肯定出了问题,要么是float要么是int,查看limits.h发现int数据大小有上限,为32767

img

另外调试也惊喜的发现各类型的数据大小:int居然为1(我觉得应该是编译器的原因,sizeof是运算符,dsp是16位的,所以int的实际大小应该是16x1,float大小为16x2)

img

解决

正确写法:包含stdint.h,使用int32_t类型,这下就能够使用32位的数据了

1
2
3
4
5
// 保留2位小数的函数
float round_to_2_decimal(float value)
{
return (float)((int32_t)(value * 100 + 0.5f)) / 100.0f;
}

当然,也可以使用F2837xd_device.h里边的类型,这里也佐证了int是16位的!

1
2
3
4
5
6
7
8
typedef int                     int16;
typedef long int32;
typedef long long int64;
typedef unsigned int Uint16;
typedef unsigned long Uint32;
typedef unsigned long long Uint64;
typedef float float32;
typedef long double float64;

总结

为了程序的兼容性和跨平台,建议统一使用stdint.h里边的类型


© 2025 hywing 使用 Stellar 创建
总访问 113701 次 | 本页访问 326