Bit fields in structure vs MACROS - any difference?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • emitrax
    New Member
    • May 2009
    • 1

    #1

    Bit fields in structure vs MACROS - any difference?

    Hi there,

    is there any difference between using bit fields structure
    and plain variable plus macros for dealing with bits?

    Let's say I have a two bytes divided as follow

    0 - 2: level
    3 - 6: type
    7 - 10: whatever
    11 - 15: future

    The two methods are

    === First Method ===
    typedef struct {
    uint16_t level: 3;
    uint16_t type: 4;
    uint16_t whatever: 4;
    uint16_t future: 5;
    } myvar;

    myvar x;
    x.level = 2;
    etc.. etc..

    === Second Method ===
    #define LEVEL(x) ( (x) & 0x0007 )
    #define TYPE(x) ( ((x) & (0x00015 << 3)) >> 3)
    #define SET_TYPE(x) & ( (x) << 3 )
    // ... whatever macro I fancy need ...
    uint16_t info;

    info |= SET_TYPE(4);


    Now beside, macros being corrected or not, is it all about personal taste
    or is there some real difference between the two methods? And if there is,
    which one is it?

    I googled for the comparison but found nothing.

    Thanks in advance!
    S.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    When you use bitfields the compiler has to generate the masking and shifting code; when you use macros you're doing that job. Not many (none?) processors can handle addressable bits so you're stuck with that bit fiddling one way or another.

    kind regards,

    Jos

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Originally posted by emitrax
      is there any difference between using bit fields structure and plain variable plus macros for dealing with bits?
      Why deal with bits at all? Declare separate integral variables for each putative bit field. This will require you to use more memory for variables, but your executable will be a little smaller and a little faster because the bit shifting and masking is not needed.

      On the other hand, perhaps your intention was for the bit fields to overlay some externally defined format (hardware register, communications protocol, file format, etc.). In that case structure bit fields are a very bad idea. You cannot portably predict how the bit fields will be arranged within the underlying integral type. Even doing your own explicit masking and shifting doesn't save you from all portability limitations: don't forget to compensate for endianness!

      Even if you need to overlay an external format, it might be best to use separate integer variables for all fields and use custom (and possibly nonportable) pack and unpack functions to interconvert to/from the external function. The rest of your program doesn't have to know as much about the external format.

      Comment

      Working...