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

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

    As has already been stated, you can't address memory smaller than a byte in C. I would write a macro:

    #define BIT(n) (1 << n)
    

    and use it to access the bits. That way, your access is the same, regardless of the size of the structure you're accessing. You would write your code as:

    if (status & BIT(1)) {
       // Do something if bit 1 is set
    } elseif (~status | BIT(2) {
       // Do something else if bit 2 is cleared
    } else  {
       // Set bits 1 and 2
       status |= BIT(1) | BIT(2)
       // Clear bits 0 and 4
       status &= ~(BIT(0) | BIT(4))
       // Toggle bit 5 
       status ^= BIT(5)
    }
    

    This gets you access close to your proposed system, which would use [] instead of ().

提交回复
热议问题