0
如何定義一個struct與union裏面,這樣它只佔用1個字節?我試圖在任何地方添加__attribute__((packed))
,但它沒有幫助。在結構中強制聯合對齊
下面是結構的成員:
struct
{
int blockNumber: 1 __attribute__((packed));
int shallBe1: 1 __attribute__((packed)); // should be set to 1 per ISO 14443-4
int nadFollowing: 1 __attribute__((packed)); // always 0 in our software
int cidFollowing: 1 __attribute__((packed)); // always 0 in our software
union
{
int chaining: 2 __attribute__((packed)); // i-block
int ackNak: 2 __attribute__((packed)); // r-block
int deselectOrWtx: 2 __attribute__((packed)); // s-block
} __attribute__((packed));
int blockType: 2 __attribute__((packed));
} pcb __attribute__((packed));
的的sizeof(PCB)返回超過1,而我需要它正好佔用一個字節。
以下是我測試結構尺寸:
BYTE testpcb[sizeof(pcb) == 1 ? 0 : -1];
如果我構建過程中出現錯誤,那麼結構是不是1個字節。
嘗試使位域「uint8_t」的基礎類型改爲(或者如果不可用,則使用「unsigned char」)。 – 2015-04-03 08:26:33
沒有運氣,大小仍然不是1個字節。 – 2015-04-03 08:29:22
每個'int'都是兩個字節,即使沒有'union',你在struct中也有五個字節。我不明白你怎麼能期待整個事情只是一個字節。 – 2015-04-03 08:44:04