Strange if statement

后端 未结 4 1433
甜味超标
甜味超标 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:23

    The & is a bitwise operator. It returns an integer with 1 bit for every bit of its two operands that are both 1, and 0 in all other places. For example:

    a = 10 # 0b1010
    b = 6  # 0b0110
    a & b  # 0b0010
    

    Now, if you have variable & 1, you're comparing variable against 0b1 which will only return 1 if that last digit in the binary representation is a 1, otherwise a 0.

提交回复
热议问题