0

let's say I have a struct:

typedef struct 
{
   uint8 value_A
   uint32 value_B
   uint32 value_C
   uint8 value_D
   3ByteType value_E
} myStructure_t 
/*Struct has 13 bytes*/

myStructure_t myStruct;

The struct is filled with values at a certain point....

I want to have an array with 13 byte - Values which represents the values from the struct

uint8 array_8ByteElements[13] = {0};

   for (uint8 idx = 0; idx <= 12; idx++)
   {
      array_8ByteElements[idx] = ??
   }

where array_8ByteElements[0] = myStruct.value_A

What is the fastest way to achieve this?

JohnDoe
  • 825
  • 1
  • 13
  • 31
  • I don't think I understand this question. How are you expecting the 13 bytes to fit into 1 byte? – Blaze Oct 29 '19 at 12:35
  • 4
    `uint8 array_8ByteElements[] = {0};` defines an array of only a *single* byte. And the loop you have iterates over *14* elements. – Some programmer dude Oct 29 '19 at 12:35
  • 5
    As for what I think the problem is, please read about [`memcpy`](https://en.cppreference.com/w/c/string/byte/memcpy). But also please read [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) I'll bet you anything that `sizeof(myStructure_t) != 13`! – Some programmer dude Oct 29 '19 at 12:36

1 Answers1

1

You could use a union:

#pragma pack(push,1)

typedef struct 
{
   uint8 value_A;
   uint32 value_B;
   uint32 value_C;
   uint8 value_D;
   b3ByteType value_E;
} myStructure_t;

typedef union {
    myStructure_t T;
    unsigned char B[sizeof(myStructure_t)];
} myUnion_t;

#pragma pack(pop)

Because of alignment, the pragmas pack set the alignment to 1 byte and after the definition sets it back to the default alignment.

I am not totally sure this will work. See also Some Programmer Dude's reference to Why isn't sizeof for a struct equal to the sum of sizeof of each member?

It may require you to redefine the order of data elements in the struct so it adheres to alignment requirements. It may require you to explicitly insert padding bytes.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41