08. May 2014 · Categories: Software

I have previously railed about the lack of support for bit fields in embedded libraries. It turns out there is a good reason for this: they are not portable, and very ill defined in the standard.

In order to provide reasonably portable implementations, we should provide a well defined alternative to bit fields, which capture the essence of what we are now doing with bit manipulation.

  • Each bit field must be based on a basic integer type. This makes the mapping to storage explicit, and reduces the chance for counting errors.
  • You can explicitly choose whether the fields start with the highest or lowest bit
  • You can specify whether the access to the field must be atomic or not
  • You can define a force value for each field. This value is written to a volatile bit field whenever you update any field, unless you specifically have changed the value in the update statement, and it also serves as the default during initialization.
  • We force the compiler to collect consecutive write statements to a field, and update the field with exactly one write, when you use the comma operator to separate the statements.

We could define define bit fields as follows:

Then we can clear either one or both of flags easily:

Things are a bit more complicated when we mix stuff:

And I wonder whether we should add new operators ->{ and .{. This would allow us to write pClear->{clear_a = 1, clear_b = 1}; to simplify updating multiple fields in one go.