Strange if statement

后端 未结 4 1552
甜味超标
甜味超标 2021-02-18 13:16

I found this strange if-statement in somebody else’s code:

if variable & 1 == 0:

I don\'t understand it. It should have two

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-18 14:01

    Your only concern is probably the operator &. It is a bitwise and which takes the binary format of the two operands and perform "logic and" on each pair of bits.

    For your example, consider the following:

    variable = 2  #0b0010
    if variable & 1 == 0:
        print "condition satisfied" # satisfied, 0b0010 & 0b0001 = 0
    
    variable = 5  #0b0101
    if variable & 1 == 0:
        print "condition satisfied" # not satisfied, 0b0101 & 0b0001 = 1
    

    Note:

    variable = 6  #0b0110
    if variable & 2 == 0:
        print "condition satisfied" # not satisfied, 0b0110 & 0b0010 = 2 (0b0010)
    

提交回复
热议问题