Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitfield masks in C

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.

like image 784
Grandpa Avatar asked Oct 10 '09 21:10

Grandpa


People also ask

What is Bitfield in structure in C?

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.

What is Bitfield in C with example?

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; };

What is mask in C programming?

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.

What is mean by Bitfield for structure?

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.


1 Answers

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;
like image 183
Keith Randall Avatar answered Sep 29 '22 05:09

Keith Randall