What does this & operator mean here?

前端 未结 5 690
南方客
南方客 2020-12-12 00:32

I was reading some tutorial about openGL in qt. One of the mouse event slot has this code in it:

if (event->buttons() & Qt::LeftButton) {    
    rota         


        
5条回答
  •  温柔的废话
    2020-12-12 01:08

    That will test that the value event=>buttons() has the bit Qt::LeftButton.

    The result would be a 0, if it did not have that bit. and a Qt::LeftButton if it did include that bit.

    it is a comparison to check the existence of a flag or bit value on a number

    0001 == 1
    0010 == 2
    0011 == 3
    
    1 & 2 == 0 (false)
    1 & 3 == 1 (true)
    2 & 3 == 2 (true)
    

    essentially it is a match across the two values for their bit values.

      (0001) 
    & (0010)
    ---------
      (0000) //Neither have the same bit
    
      (0011)
    & (0010)
    ---------
      (0010) //both have bit 2
    
      (0101)
    & (0110)
    ---------
      (0100) // Both have the 3rd bit
    
      (0111)
    & (0110)
    ---------
      (0110) // Both have the 2nd and 3rd bit
    

    Boolean values in C languages are 0 for false. and anything non zero is true.

    This proved that the 1st and 2nd bit are available in the number 3. however 1 and 2 do not have matching bits.

    Look into bitwise operators. to get a better understanding.

    http://en.wikipedia.org/wiki/Bitwise_operation

提交回复
热议问题