When is it worthwhile to use bit fields?

Bit-fields are typically only used when there’s a need to map structure fields to specific bit slices, where some hardware will be interpreting the raw bits. An example might be assembling an IP packet header. I can’t see a compelling reason for an emulator to model a register using bit-fields, as it’s never going to touch real hardware!

Whilst bit-fields can lead to neat syntax, they’re pretty platform-dependent, and therefore non-portable. A more portable, but yet more verbose, approach is to use direct bitwise manipulation, using shifts and bit-masks.

If you use bit-fields for anything other than assembling (or disassembling) structures at some physical interface, performance may suffer. This is because every time you read or write from a bit-field, the compiler will have to generate code to do the masking and shifting, which will burn cycles.

Leave a Comment