我想从 32 位寄存器中读取第 2、5 和 6 位。我决定使用结构位字段来存储它们。以下数据结构是否正确?
struct readData
{
int unwanted:1;
int reqbit1:1;
int unwanted1:2;
int reqbit2:2;
int unwanted2:26;
};
我不确定位域是如何创建的。我将使用一个 API 将字节从 h/w 寄存器直接复制到这个结构。在那种情况下,reqbit1 会包含第二位吗?据我了解,编译器将第一位分配给一个 int 变量,第二位分配给另一个 int 变量,因此 reqbit1 不会从寄存器中读取任何数据。下面的union不是更适合这种情况吗?
union readData
{
struct readBits
{
bool unwanted:1;
bool reqbit1:1;
xxx unwanted1:2;
short reqbit2:2;
xxx unwanted2:26;
};
int regValue;
};
如果这是正确的,我应该将 unwanted2 声明为什么?
最佳答案
通常使用以下 union :
union readData {
struct {
unsigned int unwanted:1;
unsigned int reqbit1:1;
unsigned int unwanted1:2;
unsigned int reqbit2:2;
unsigned int unwanted2:26;
} readBits;
unsigned int regValue;
};
编辑:
用法是:
#define REG_ADDRESS 0x12345678 // e.g.
union readData* rd = (union readData*)REG_ADDRESS;
char bit2 = rd->readBits.reqbit1;
char bits56 = rd->readBits.reqbit2;
关于c - 用于从 H/W 寄存器读取的位字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541370/