Is there a way to access individual bits with a union?

前端 未结 6 927
日久生厌
日久生厌 2021-02-01 21:44

I am writing a C program. I want a variable that I can access as a char but I can also access the specific bits of. I was thinking I could use a union like this...



        
6条回答
  •  既然无缘
    2021-02-01 22:32

    Sure, but you actually want to use a struct to define the bits like this

    typedef union
    {
      struct
      {
        unsigned char bit1 : 1;
        unsigned char bit2 : 1;
        unsigned char bit3 : 1;
        unsigned char bit4 : 1;
        unsigned char bit5 : 1;
        unsigned char bit6 : 1;
        unsigned char bit7 : 1;
        unsigned char bit8 : 1;
      }u;
      unsigned char status;
    }DeviceStatus;
    

    Then you can access for DeviceStatus ds; you can access ds.u.bit1. Also, some compilers will actually allow you to have anonymous structures within a union, such that you can just access ds.bit1 if you ommit the u from the typedef.

提交回复
热议问题