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...
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 ().