gpt4 book ai didi

c - 这个位域会按我预期的方式工作吗?

转载 作者:太空狗 更新时间:2023-10-29 15:33:36 24 4
gpt4 key购买 nike

我一直在阅读有关 C 中的位域的一些资料,C 标准如何不强制执行机器字中字段的任何特定顺序,等等。

我希望这个问题适合 SO 的格式。

我的问题是我的结构(定义如下)是否会按照我期望的方式执行。这是我想出的定义,然后我将讨论我想要什么:

typedef enum {
STATE_ONE,
STATE_TWO,
STATE_THREE,
STATE_FOUR
} __attribute__ ((packed)) State;

typedef struct MyStruct {
// One of State enum (maximum of 4 states).
unsigned state : 2;

// Remaining 30 bits are used differently depending on 'state'.
union {
// If 'state' is STATE_ONE (0), the remaining bits are an ID number.
unsigned id : 30;

/*
* For all other states, the remaining bits are the 2-tuple:
* (buffer A index, buffer B index).
*/
struct {
unsigned bufferAIdx : 16;
unsigned bufferBIdx : 14;
} __attribute__ ((packed)) index;
} __attribute__ ((packed));
} __attribute__ ((packed)) MyStruct;

(这是针对 gcc 的,因此是 __attribute__ 指令)。

您可能会知道我要做什么:根据“状态”字段的值,我想将剩余的 30 位用于不同的目的。它们应该是一个 ID 号,或者是各种缓冲区的索引的 2 元组。 并且,MyStruct 的每个实例最多应适合 5 个字节。

所以我想做的就是达到这种效果:

MyStruct a, b;
a.state = STATE_ONE;
a.id = 123456;

b.state = STATE_THREE;
b.index.bufferAIdx = 6;
b.index.bufferBIdx = 2;

主要是我在寻找关于这是否是“正确的事情”的意见。换句话说,我在这里滥用了位域/union 的想法吗?如果您要成为此代码的维护者,看到此内容您会惊恐地畏缩吗?或者,您是否希望看到整个数据对象存储在 uint32_t 类型中并通过屏蔽和移位进行操作?

最佳答案

由于任何 unionstruct 的开头都将在边界上对齐,因此您无法以这种方式将所有数据放入 32 位。您应该以相反的方式封装您的 unionstruct,如下所示(为了便于阅读而删除了属性):

typedef struct MyStruct {
union {
struct {
unsigned state : 2;
unsigned id : 30;
}
struct {
unsigned /* unused */ : 2;
unsigned bufferAIdx : 16;
unsigned bufferBIdx : 14;
};
};
};

关于c - 这个位域会按我预期的方式工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com