Macros to get and set a bit field within a value

Ricky Bennett March 22, 2013 Coded in C

GetField retrieves the bit field and shifts it down to bit 0.

SetField removes the old bit field value, and masks, shifts, and stores the new bit field value.

The macro parameters:

     Var    = Variable containing the bit field.
     Mask = Unshifted bit field mask.  If 3 bits are used, the mask is 0x7.
     Shift  = Bit field shift count.
     Val    = Value of the new bit field (SetField only).

// Get a bit field from a value
#define GetField(Var, Mask, Shift) \
      (((Var) >> (Shift)) & (Mask))

// Set a bit field in a value
#define SetField(Var, Mask, Shift, Val) \
      (Var) = (((Var) & ~((Mask) << (Shift))) | (((Val) & (Mask)) << (Shift)))