I came across the following code
numdigits = len(cardNumber)
oddeven = numdigits & 1
what exactly is going on here? I’m not sure what the "&" is doing.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Answer
The
&symbol is a bitwise AND operator. Used with 1, it basically masks the value to extract the lowest bit, or in other words will tell you if the value is even or odd.More Info on Python’s
&operatorFor more information, see: http://wiki.python.org/moin/BitwiseOperators
Why it Works to check Odd vs. Even
EDIT: Adding this section since this answer is getting some love
The reason why ANDing a value with 1 tells if the value is odd or even may not be obvious at first.
The binary representation of a number is essentially the sum of a series of YES or NO for each power of 2 moving leftward starting in the rightmost digit with 1, 2, 4, 8, …
There is only one way to represent any number in this way. E.g. the number 13 (base 10) can be written in binary as “1101” (or hexadecimal as 0xD, but that’s beside the point). See here:
Notice that aside from the rightmost binary digit, all other
1digits will add an even number (i.e. a multiple of 2) to the sum. So the only way to get an odd final sum is to add that odd 1 from the rightmost digit. So if we’re curious if a number is odd or even, we can look at its binary representation and ignore everything except for the rightmost digit.To do this, we use the bitwise AND operator. The value
1in binary is expressed as1:ANDing a value with
1like this will result in1if the value’s rightmost bit is set, and0if it is not.And because
0is generally considered “false” in most languages, and non-zero values considered “true”, we can simply say as a shortcut: