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...
The smallest unit that is addressable in C is always a byte (called char
in C). You cannot access a bit directly. The closest way to get to accessing bits would be to define a data type called bitpointer
and define some functions or macros for it:
#include
typedef struct bitpointer {
unsigned char *pb; /* pointer to the byte */
unsigned int bit; /* bit number inside the byte */
} bitpointer;
static inline bool bitpointer_isset(const bitpointer *bp) {
return (bp->pb & (1 << bp->bit)) != 0;
}
static inline void bitpointer_set(const bitpointer *bp, bool value) {
unsigned char shifted = (value ? 1 : 0) << bp->bit;
unsigned char cleared = *bp->pb &~ (1 << bp->bit);
*(bp->pb) = cleared | shifted;
}
I recommend against unions because it is implementation-defined whether they are filled msb-to-lsb or lsb-to-msb (see ISO C99, 6.7.2.1p10).