是否与工会访问各个位的方法吗? [英] Is there a way to access individual bits with a union?
问题描述
我写一个C程序。我想,我可以访问作为一个char,但我还可以访问的特定位的变量。我想我可以用一个工会这样的...
I am writing a C program. I want a variable that I can access as a char but I can also access the specific bits of. I was thinking I could use a union like this...
typedef union
{
unsigned char status;
bit bits[8];
}DeviceStatus;
但是编译器不喜欢这样。显然,你不能在一个结构使用位。
所以,我能做些什么呢?
but the compiler doesn't like this. Apparently you can't use bits in a structure. So what can I do instead?
推荐答案
当然,但你真的想使用结构来定义这样的位
Sure, but you actually want to use a struct to define the bits like this
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;
然后,你可以访问 DeviceStatus DS;
您可以访问 ds.u.bit1
。此外,一些编译器实际上将让你有一个联盟内的匿名结构,这样你可以访问 ds.bit1
如果您ommit从类型定义的U
Then you can access for DeviceStatus ds;
you can access ds.u.bit1
. Also, some compilers will actually allow you to have anonymous structures within a union, such that you can just access ds.bit1
if you ommit the u from the typedef.
这篇关于是否与工会访问各个位的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!