When is it worthwhile to use bit fields?

前端 未结 11 590
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:10

Is it worthwhile using C\'s bit-field implementation? If so, when is it ever used?

I was looking through some emulator code and it looks like the registers for the c

11条回答
  •  粉色の甜心
    2020-12-01 09:43

    An alternative to consider is to specify bit field structures with a dummy structure (never instantiated) where each byte represents a bit:

    struct Bf_format
    {
      char field1[5];
      char field2[9];
      char field3[18];
    };
    

    With this approach sizeof gives the width of the bit field, and offsetof give the offset of the bit field. At least in the case of GNU gcc, compiler optimization of bit-wise operations (with constant shifts and masks) seems to have gotten to rough parity with (base language) bit fields.

    I have written a C++ header file (using this approach) which allows structures of bit fields to be defined and used in a performant, much more portable, much more flexible way: https://github.com/wkaras/C-plus-plus-library-bit-fields . So, unless you are stuck using C, I think there would rarely be a good reason to use the base language facility for bit fields.

提交回复
热议问题