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

前端 未结 10 1133
花落未央
花落未央 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:42

    You can use an AND operator. The example you have: 10101010 and you want to check the third bit you can do: (10101010 AND 00100000) and if you get 00100000 you know that you have the flag at the third position to 1.

    0 讨论(0)
  • 2020-12-08 05:43

    If you are using C++ and the standard library is allowed, I'd suggest storing your flags in a bitset:

    #include <bitset>
    //...
    std::bitset<8> flags(someVariable);
    

    as then you can check and set flags using the [] indexing operator.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-08 05:46

    Nobody's been wrong so far, but to give a method to check an arbitrary bit:

    int checkBit( byte in, int bit )
    {
      return in & ( 1 << bit );
    }
    

    If the function returns non-zero, the bit is set.

    0 讨论(0)
提交回复
热议问题