Converting a struct of 4 integers to a float

  • A+

I am new to programming and I am not strong in pointers and typecasting, so I need some help.

I am using IAR Workbench and STM32L475. I am trying to convert 4 bytes in a struct to a float, after loading them from an Eeprom.

I know there can be challenges with Big/Little Endian and portability of code to other micro's but please do not clutter this thread with that as this is not important for me right now.

What am I doing wrong, thanks for helping?

Please keep it simple and explain "for dummies".

I am getting pe513 error.

My code:

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; } 

Edit: I am loading an array from an Eeprom and must "collect" an array of four uint8 bytes to a float, they were a part of a struct before they were saved to the Eeprom. I will update with the exact error message when I get to work tomorrow.

I ended up using "union" as this seems to be the best solution.

My sample code looks like this now:

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]); } 

And the output looks like this:

floatvalue 23.10  Byte1 cd Byte2 cc Byte3 b8 Byte4 41 Array[0] cd Array[1] cc Array[2] b8 Array[3] 41 


You could use a union:

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 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: