我有一个类似于以下内容的联盟:
typedef
union _thing
{
struct thing_indiv {
uint16_t one:5;
uint16_t two:4;
uint16_t three:5;
uint16_t four:5;
uint16_t five:6;
uint16_t six:6;
uint16_t seven:6;
uint16_t eight:7;
uint16_t nine:4;
uint16_t ten:5;
uint16_t eleven:6;
uint16_t twelve:5;
uint16_t thirteen:5;
uint16_t fourteen:4;
uint16_t fifteen:2;
uint16_t unused:5;
} __attribute__((packed)) thing_split;
uint8_t thing_comb[10];
} thing;
但它的表现并不符合我的期望。我希望将字节分配给thing.thing_comb
,并从thing.thing_split
检索相关的项。
例如,如果我期望thing.thing_split.one包含0x1A
( 0xD6
的5个最高有效位,但它没有,它包含0x16
,5个最低有效位。我将每个字段声明为uint16_t
,以防止gcc抱怨跨越字节边界(我在使用uint8_t
时也经历了同样的行为)。
有没有一种方法来布局这个结构来获得这种行为?
发布于 2020-11-16 18:31:37
首先,在C++中使用联合的类型双关语是未定义的行为。其次,编译器可以自由地使用位域做任何它想做的事情。它不会像你想要的那样被强迫去布局。
你需要使用常规的位打包和位移位来获得你想要的行为。
不久前我遇到过一个类似的问题:How to use bitfields that make up a sorting key without falling into UB?
https://stackoverflow.com/questions/64863500
复制相似问题