[英]C: Cast byte array to struct
I have the problem of casting a byte array to a struct, some bytes are ignored or skipped. 我有一个将字节数组转换为结构的问题,忽略或跳过一些字节。
Given the following struct, 鉴于以下结构,
typedef struct
{
uint32_t id;
uint16_t test;
uint8_t group;
uint32_t time;
uint16_t duration;
uint8_t a;
uint8_t b;
uint8_t c;
uint16_t d;
uint16_t e;
uint8_t status;
uint8_t x;
uint8_t y;
} testStruct_t, *PtestStruct_t;
I have an array with the following test data: 我有一个包含以下测试数据的数组:
uint8_t pBuff = { 0x11 , 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19 };
The casting is done as follows: 铸造如下:
PtestStruct_t pStruct = (PtestStruct_t)pBuff;
Somewhere in the structure some bytes are skipped or ignored. 在结构的某处,某些字节被跳过或忽略。 I do not know why.
我不知道为什么。 This has been tested in Visual Studio 2012 and on a ARM processor on which this testing and debugging was made required.
这已经在Visual Studio 2012和需要进行此测试和调试的ARM处理器上进行了测试。
What am I missing here? 我在这里错过了什么? I do not believe it is Endian related.
我不相信它与Endian有关。 It could be the compiler in both test cases, I do not know what to do in this last case.
它可能是两个测试用例中的编译器,我不知道在最后一种情况下该怎么做。
The bytes which are being skipped/ignored are 0x88
and 0x14
被跳过/忽略的字节是
0x88
和0x14
You're encountering alignment padding. 你遇到了对齐填充。
uint32_t id; // offset 0
uint16_t test; // offset 4
uint8_t group; // offset 6
uint32_t time; // offset 7
The offsets shown here are likely to be wrong. 此处显示的偏移可能是错误的。 The compiler will probably place padding between "group" and "time" to ensure that "time" is on a 4-byte boundary (the actual alignment is configurable)
编译器可能会在“组”和“时间”之间放置填充,以确保“时间”在4字节边界上(实际对齐是可配置的)
If you absolutely require the structure to be like that, you can use #pragma pack
如果你绝对要求结构是这样的,你可以使用
#pragma pack
#pragma pack(push, 1)
typedef struct
{
uint32_t id;
uint16_t test;
uint8_t group;
uint32_t time;
uint16_t duration;
uint8_t a;
uint8_t b;
uint8_t c;
uint16_t d;
uint16_t e;
uint8_t status;
uint8_t x;
uint8_t y;
} testStruct_t, *PtestStruct_t;
#pragma pack(pop)
Compiler may have added some byte between your struct fields for alignment. 编译器可能在您的struct字段之间添加了一些字节以进行对齐。 You need to use a packing to prevents compiler from doing padding - this has to be explicitly requested - under GCC it's attribute (( packed )),
您需要使用打包来阻止编译器执行填充 - 这必须明确请求 - 在GCC下它的属性 (( 压缩 )),
example: 例:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.