问题
I thought that using a C bitfield instead of a int
along with a bunch of #define
s would give a better-to-read code and reduce the need for adapting existing code when adding new fields. Is there any possibility to reset all Bits in a C bitfield to zero with a single command as the int
-#define
-method provides?
Examples:
#define MYFLAG_1 0x01
#define MYFLAG_2 0x02
#define MYFLAG_3 0x04
int myflags = MYFLAG_1 | MYFLAG_3;
/* Reset: */
myflags = 0;
versus
struct {
int flag_1 : 1;
int flag_2 : 1;
int flag_3 : 1;
} myflags;
myflags.flag_1 = 1;
myflags.flag_3 = 1;
/* Reset: */
myflags.flag_1 = 0;
myflags.flag_2 = 0;
myflags.flag_3 = 0;
Adding an additional flag to the field would require no change (apart from the #define) in the existing code of the first example but would require code to reset the additional flag field.
回答1:
I would simply suggest:
memset(&my_flags, 0, sizeof(myflags));
This way, you can still add fields to your structure, they will be reset thanks to sizeof
.
回答2:
I'd like to expand my comment to an answer:
Using a union, you can have a numerical variable and your bit field sharing the same memory:
typedef union{
struct {
int flag_1 : 1;
int flag_2 : 1;
int flag_3 : 1;
};
unsigned int value;
} MyBitField;
// ...
MyBitField myflags;
myflags.flag_1 = 1;
myflags.flag_3 = 1;
/* Reset: */
//myflags.flag_1 = 0;
//myflags.flag_2 = 0;
//myflags.flag_3 = 0;
myflags.value = 0;
Now, you can easily set all bits to 0. The union will always occupy the amount of memory the largest object in it needs. So, if you need more bits than an INT has, you may also use a long
or long long
.
I haven't seen unions in "computer programming" until now, but for microcontrollers, they are used quite often.
来源:https://stackoverflow.com/questions/27121427/reset-all-bits-in-a-c-bitfield