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

前端 未结 6 933
日久生厌
日久生厌 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:11

    You have a couple of possibilities. One would be to just use Boolean math to get at the bits:

    int bit0 = 1;
    int bit1 = 2;
    int bit2 = 4;
    int bit3 = 8;
    int bit4 = 16;
    int bit5 = 32;
    int bit6 = 64;
    int bit7 = 128;
    
    if (status & bit1)
        // whatever...
    

    Another is to use bitfields:

    struct bits { 
       unsigned bit0 : 1;
       unsigned bit1 : 1;
       unsigned bit2 : 1;
    // ...
    };
    
    typedef union {
        unsigned char status;
        struct bits bits;
    } status_byte;
    
    some_status_byte.status = whatever;
    if (status_byte.bits.bit2)
        // whatever...
    

    The first is (at least arguably) more portable, but when you're dealing with status bits, chances are that the code isn't even slightly portable anyway, so you may not care much about that...

提交回复
热议问题