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?

3
  • I don't think I understand this question. How are you expecting the 13 bytes to fit into 1 byte? Commented Oct 29, 2019 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. Commented Oct 29, 2019 at 12:35
  • 5
    As for what I think the problem is, please read about memcpy. But also please read Why isn't sizeof for a struct equal to the sum of sizeof of each member? I'll bet you anything that sizeof(myStructure_t) != 13! Commented Oct 29, 2019 at 12:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There is 24 bit padding between value_A and value_B, so the bytes won't be continuous.
@JorgeBellon, hence the pragmas. These give the expected result using MSC2008.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.