简体   繁体   English

将具有不同类型的结构中的值复制到 1 字节值数组

[英]Copy value from struct with different types to an 1-Byte values array

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我想要一个 13 字节的数组 - Values 代表结构中的值

uint8 array_8ByteElements[13] = {0};

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

where array_8ByteElements[0] = myStruct.value_A其中 array_8ByteElements[0] = myStruct.value_A

What is the fastest way to achieve this?实现这一目标的最快方法是什么?

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.由于 alignment,编译指示pack将 alignment 设置为 1 字节,并在定义后将其设置回默认值 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?另请参阅 Some Programmer Dude 对Why is not sizeof for a struct 的 reference 等于每个成员的 sizeof 的总和?

It may require you to redefine the order of data elements in the struct so it adheres to alignment requirements.它可能需要您重新定义结构中数据元素的顺序,以使其符合 alignment 要求。 It may require you to explicitly insert padding bytes.它可能需要您显式插入填充字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM