4 bit field code example

Example: c bit access struct

typedef union a429_tag { // define a union of structs and/or raw data types
  // struct to access each bit individually
  struct {
    unsigned int
        bit0  : 1, bit1  : 1, bit2  : 1, bit3  : 1,
        bit4  : 1, bit5  : 1, bit6  : 1, bit7  : 1,
        bit8  : 1, bit9  : 1, bit10 : 1, bit11 : 1,
        bit12 : 1, bit13 : 1, bit14 : 1, bit15 : 1;
  };
  // struct to access range of bits by name
  struct {
    unsigned int
        label  : 8,
        sdi    : 2,
        data   : 3,
        ssm    : 2,
        parity : 1;
  };
  // int type to access to the entire word as an integer
  unsigned int word : 16;
  
} a429_type;

/* Example usage */
int main() {
  a429_type myUnion;
  myUnion.parity = 1;
  if (myUnion.bit15 == 1) {
    printf("parity and bit15 refer to the same bit");
  }
  return 0;
}

Tags:

C Example