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

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

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

提交回复
热议问题