簡體   English   中英

C:將字節數組轉換為struct

[英]C: Cast byte array to 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;

我有一個包含以下測試數據的數組:

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

鑄造如下:

PtestStruct_t pStruct = (PtestStruct_t)pBuff;

在結構的某處,某些字節被跳過或忽略。 我不知道為什么。 這已經在Visual Studio 2012和需要進行此測試和調試的ARM處理器上進行了測試。

我在這里錯過了什么? 我不相信它與Endian有關。 它可能是兩個測試用例中的編譯器,我不知道在最后一種情況下該怎么做。

被跳過/忽略的字節是0x880x14

你遇到了對齊填充。

uint32_t id;     // offset 0
uint16_t test;   // offset 4
uint8_t group;   // offset 6
uint32_t time;   // offset 7

此處顯示的偏移可能是錯誤的。 編譯器可能會在“組”和“時間”之間放置填充,以確保“時間”在4字節邊界上(實際對齊是可配置的)

如果你絕對要求結構是這樣的,你可以使用#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)

編譯器可能在您的struct字段之間添加了一些字節以進行對齊。 您需要使用打包來阻止編譯器執行填充 - 這必須明確請求 - 在GCC下它的屬性 (( 壓縮 )),

例:

      struct __attribute__((__packed__)) mystruct_A {
      char a;
      int b;
     char c;
     };

並為Visual Studio咨詢MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM