What does & mean in python

前端 未结 5 2429
长情又很酷
长情又很酷 2020-11-28 08:20

Hi I came across the following code

numdigits = len(cardNumber)
oddeven = numdigits & 1

what exactly is going on here? I\'m not sure wh

5条回答
  •  春和景丽
    2020-11-28 09:06

    It's a bitwise operation, in this case assigning zero to oddeven if cardNumber has an even number of elements (and one otherwise).

    As an example: suppose len(cardNumber) == 235. Then numdigits == 235, which is 0b11101011 in binary. Now 1 is '0b00000001' in binary, and when you "AND" them, bitwise, you'll get:

      11101011
      &
      00000001
      ----------
    = 00000001
    

    Similarly, if numdigits were 234, you would get:

      11101010
      &
      00000001
      ----------
    = 00000000
    

    So, it's basically a obfuscated way of checking if len(cardNumber) % 2. Probably written by someone with a C background, because it is not very pythonic - readability counts!

提交回复
热议问题