将4个整数的结构转换为浮点数

Pet*_*er1 1 c pointers type-conversion stm32

我是编程新手,我在指针和类型转换方面不强,所以我需要一些帮助.

我正在使用IAR Workbench和STM32L475.我试图将结构中的4个字节转换为浮点数,然后从Eeprom加载它们.

我知道Big/Little Endian可能存在挑战,并且代码可以移植到其他微软,但请不要因为这对我来说不重要,因为这对我来说并不重要.

我做错了什么,谢谢你的帮助?

请保持简单并解释"为傻瓜".

我收到了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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我正在从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]);
}
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

floatvalue 23.10 
Byte1 cd
Byte2 cc
Byte3 b8
Byte4 41
Array[0] cd
Array[1] cc
Array[2] b8
Array[3] 41
Run Code Online (Sandbox Code Playgroud)

P__*_*J__ 7

联盟惩罚会做.

typedef union
{
    uint32_t u32;
    uint16_t u16[2];
    uint8_t  u8[4];
    float    f;
}b32data;
Run Code Online (Sandbox Code Playgroud)

当你从NV内存中读取时,只需指定正确的成员而不需要任何指针.


Mik*_*ike 5

你可以使用一个联盟:

typedef union
{
    struct
    {
        uint8_t Byte1;
        uint8_t Byte2;
        uint8_t Byte3;
        uint8_t Byte4;
     };
     float      floatvalue;
}TestT;

TestT   Test;

Test.floatvalue = ......    //complete float
Test.Byte1 = .....          //single Byte to save in EEPROM
Run Code Online (Sandbox Code Playgroud)


use*_*733 5

由于您不关心可移植性或字节顺序问题,因此您可以简单地使用以下命令复制字节memcpy

memcpy(&x, &TestStruct, sizeof x);
Run Code Online (Sandbox Code Playgroud)

您可能在某处看到过此选项或类似选项:

x = *(float*)&TestStruct;  // BAD!!!!! dereferencing using wrong pointer type
Run Code Online (Sandbox Code Playgroud)

不要这样做!它违反了严格的别名规则,这是未定义的行为