C++ meaning |= and &=

后端 未结 7 1440

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:15

    x |= y is equivalent to x = x|y

    In general, for any binary operator *, a *= b is equivalent to a = a*b

    If you want to know what & and | are, read about bitwise operators.

    0 讨论(0)
  • 2020-12-20 08:20

    &= |= operators in a sense are similar to +=/-= (i.e. a &= b is equivalent to a = a & b). But, they do binary operations. & is doing bitwise and operation, while | is doing bitwise or operation.

    Example:

    a = 1101

    b = 1011

    a & b = 1001

    a | b = 1111

    0 讨论(0)
  • 2020-12-20 08:20

    x |= y specifically turns on (sets to 1) those bits in x present in y, leaving all the others in x as they were.

    x &= ~y specifically turns off (sets to 0) those bits in x present in y, leaving all the others in x as they were.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-20 08:27

    it's a simple way to set & reset specific bit in a word.

    bitword |= MASK is a shorthand of bitword = bitword | MASK which sets the mask bit

    bitword &= ~MASK clears that bit (check your boolean algebra notebook to see why)

    0 讨论(0)
  • 2020-12-20 08:33

    These are bitwise AND and OR operations. The lines you mentioned are equivalent to:

    m_controlState = m_controlState | TDC_LEFT;
    m_controlState = m_controlState & ~TDC_LEFT
    
    0 讨论(0)
提交回复
热议问题