C++ meaning |= and &=

后端 未结 7 1439

I have a part of code that contains the following functions:

void Keyboard(int key)
{
    switch (key) {
    case GLFW_KEY_A: m_controlState |= TDC_LEFT; bre         


        
7条回答
  •  囚心锁ツ
    2020-12-20 08:21

    These two:

    m_controlState |= TDC_LEFT
    m_controlState &= ~TDC_LEFT
    

    are equivalent to:

    m_controlState = m_controlState | TDC_LEFT
    m_controlState = m_controlState & ~TDC_LEFT
    

    It works like this with all builtin X= operators.

    m_controlState is most likely treated as a bitset. m_controlState may be, e.g. 01010000 (realistically, it will be larger than 8 bits).

    1) | is bitwise or, which is equivalent to addition to that bitset.

    So if TDC_LEFT is 00000010:

    01010000 | 00000010 = 01010010
    

    2) ~ is bitwise negation:

    ~00000010 = 111111101
    

    And if you do 01010010 & ~(00000010) = 01010000, it's effectively equivalent to bitset difference.

    In short:

    bitsetA + bitsetB <=> bitsetA | bitset
    bitsetA - bitsetB <=> bitsetA & ~ bitset
    

提交回复
热议问题