【发布时间】:2019-01-21 07:03:52
【问题描述】:
我是编程新手,我不擅长指针和类型转换,所以我需要一些帮助。
我正在使用 IAR Workbench 和 STM32L475。 在从 EEprom 加载它们之后,我正在尝试将结构中的 4 个字节转换为浮点数。
我知道 Big/Little Endian 和将代码移植到其他 micro's 可能会遇到挑战,但请不要把这个线程弄乱,因为这对我来说现在并不重要。
我做错了什么,谢谢你的帮助?
请保持简单并解释“傻瓜”。
我收到 pe513 错误。
我的代码:
struct Test {
uint8_t Byte1;
uint8_t Byte2;
uint8_t Byte3;
uint8_t Byte4;
} TestStruct;
float x = 0.0;
uint8_t *TestStruct_ptr;
int main(void)
{
/* USER CODE BEGIN 1 */
TestStruct.Byte1 = 0x41; //float value = 23.10
TestStruct.Byte2 = 0xB8;
TestStruct.Byte3 = 0xCC;
TestStruct.Byte4 = 0xCD;
TestStruct_ptr = (float*)&TestStruct;
x = (float*) TestStruct_ptr;
// some code
return 0;
}
编辑: 我正在从 Eeprom 加载一个数组,并且必须将四个 uint8 字节的数组“收集”到一个浮点数,它们在保存到 Eeprom 之前是结构的一部分。 明天上班时,我会更新确切的错误消息。
我最终使用了“联合”,因为这似乎是最好的解决方案。
我的示例代码现在如下所示:
union Eeprom {
struct {
uint8_t Byte1;
uint8_t Byte2;
uint8_t Byte3;
uint8_t Byte4;
};
float x;
uint8_t Array[4];
};
int main(void)
{
union Eeprom Test;
//assign values to individual bytes
Test.Byte1=0xCD;
Test.Byte2=0xCC;
Test.Byte3=0xB8;
Test.Byte4=0x41;
//Assign values as an array (here individual bytes, overwrites above assigned values).
//Data will be formatted as an array when loaded from E2prom.
Test.Array[0]=0xCD;
Test.Array[1]=0xCC;
Test.Array[2]=0xB8;
Test.Array[3]=0x41;
//Assign value as floating point value (overwrites the above assigned values)
Test.x = 23.1;
printf("FPvalue %3.2f \n Byte1 %x\n Byte2 %x\n Byte3 %x\n Byte4 %x\n
Array[0] %x\n Array[1] %x\n Array[2] %x\n Array[3] %x\n",
Test.x, Test.Byte1, Test.Byte2, Test.Byte3, Test.Byte4,
Test.Array[0], Test.Array[1], Test.Array[2], Test.Array[3]);
}
输出如下所示:
floatvalue 23.10
Byte1 cd
Byte2 cc
Byte3 b8
Byte4 41
Array[0] cd
Array[1] cc
Array[2] b8
Array[3] 41
【问题讨论】:
-
“我收到 pe513 错误。” 这太神秘了,任何人都无法记住它的含义。请edit 并在您的问题中添加完整错误消息。
-
TestStruct_ptr = (float*)&TestStruct;violates strict aliasing 是未定义的行为。TestStruct不是float并且不能作为一个来处理。 -
我不清楚。您是想将 4
int转换为 4float、4int转换为单个float,还是将整个struct内容转换为单个float值? -
为什么不用float类型而不是把数据类型从int改成float呢?
-
@Lundin 假设
address当然是正确对齐的!
标签: c pointers type-conversion stm32