Is there a portable way in C to find out the mask for a bit field at compile time?
Ideally, I'd like to be able to atomically clear a field like this:
struct Reference {
unsigned age : 3;
unsigned marked : 1;
unsigned references : 4;
};
struct Reference myRef;
__sync_and_and_fetch(&myRef, age, ~AGE_MASK);
Otherwise I have to take out a lock on the struct, which is more heavyweight than I'd like.
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
Declaration of bit-fields in CThe number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type. Example: struct date { // month has value between 0 and 15, // so 4 bits are sufficient for month variable. int month : 4; };
In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word, etc. can be set either on or off, or inverted from on to off (or vice versa) in a single bitwise operation.
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected.
Or, if you really wanted the mask:
union Reference {
unsigned asWord;
struct {
unsigned age : 3;
unsigned marked : 1;
unsigned references : 4;
} asFields;
}
Reference agemask_ref;
agemask_ref.asFields = (typeof(agemask_ref.asFields)){0, -1, -1};
unsigned agemask = agemask_ref.asWord;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With