PIC*_*ain 16 c bits structure unions
我正在写一个C程序.我想要一个我可以作为char访问的变量,但我也可以访问特定的位.我以为我可以使用像这样的联盟......
typedef union
{
unsigned char status;
bit bits[8];
}DeviceStatus;
Run Code Online (Sandbox Code Playgroud)
但编译器不喜欢这个.显然你不能在结构中使用位.那么我该怎么做呢?
tor*_*rak 22
当然,但你真的想用一个结构来定义这样的位
typedef union
{
struct
{
unsigned char bit1 : 1;
unsigned char bit2 : 1;
unsigned char bit3 : 1;
unsigned char bit4 : 1;
unsigned char bit5 : 1;
unsigned char bit6 : 1;
unsigned char bit7 : 1;
unsigned char bit8 : 1;
}u;
unsigned char status;
}DeviceStatus;
Run Code Online (Sandbox Code Playgroud)
然后您可以访问,DeviceStatus ds;您可以访问ds.u.bit1.此外,一些编译器实际上允许您在联合中使用匿名结构,这样ds.bit1如果您从typedef中省略u,则可以访问它.
你有几种可能性。一种方法是仅使用布尔数学来获取这些位:
int bit0 = 1;
int bit1 = 2;
int bit2 = 4;
int bit3 = 8;
int bit4 = 16;
int bit5 = 32;
int bit6 = 64;
int bit7 = 128;
if (status & bit1)
// whatever...
Run Code Online (Sandbox Code Playgroud)
另一种是使用位域:
struct bits {
unsigned bit0 : 1;
unsigned bit1 : 1;
unsigned bit2 : 1;
// ...
};
typedef union {
unsigned char status;
struct bits bits;
} status_byte;
some_status_byte.status = whatever;
if (status_byte.bits.bit2)
// whatever...
Run Code Online (Sandbox Code Playgroud)
第一个(至少可以说)更可移植,但是当您处理状态位时,很可能代码无论如何都没有一点可移植性,所以您可能不太关心这一点......