c bit access union 1

c bit access union

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;
}

Here is what the above code is Doing:
1. Define a union called a429_type.
2. Define a struct called bit_struct that allows you to access each bit individually.
3. Define a struct called label_struct that allows you to access a range of bits by name.
4. Define an int type called word that allows you to access the entire word as an integer.
5. Create a variable called myUnion of type a429_type.
6. Set the parity bit to 1.
7. Check if the parity bit is set.

Similar Posts