How can I check my byte flag, verifying that a specific bit is at 1 or 0?

前端 未结 10 1178
花落未央
花落未央 2020-12-08 05:11

I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.

10条回答
  •  鱼传尺愫
    2020-12-08 05:45

    Here's a function that can be used to test any desired bit:

    bool is_bit_set(unsigned value, unsigned bitindex)
    {
        return (value & (1 << bitindex)) != 0;
    }
    

    A bit of explanation:

    The left shift operator (<<) is used to create a bit mask. (1 << 0) will be equal to 00000001, (1 << 1) will be equal to 00000010, (1 << 3) will be equal to 00001000, etc. So a shift of 0 tests the rightmost bit. A shift of 31 would be the leftmost bit of a 32-bit value.

    The bitwise-and operator (&) gives a result where all the bits that are 1 on both sides are set. Examples: 1111 & 0001 = 0001; 1111 & 0010 == 0010; 0000 & 0001 = 0000. So, the expression (value & (1 << bitindex)) will return the bitmask if the associated bit is 1 in value, or will return 0 if the associated bit is 0.

    Finally, we just check whether the result is non-zero. (This could actually be left out, but I like to make it explicit.)

提交回复
热议问题