Understanding Python Bitwise, Arithmetic, And Boolean Operators
Solution 1:
The expression is evaluated as n += (parity != (n & 1)), and the results are:
n & 1is a bitmask, it masks the integerndown to the least-significant bit. Ifnis odd, it will be1, if it is even, that bit will be0.parity != 0orparity != 1produces a boolean result,TrueorFalse, signalling ifparitywas not equal to the0or1on the right.The resulting
TrueorFalseis added up ton, as if you didn = n + Trueorn = n + False. The Python boolean type is a subclass ofintandFalsehas an integer value of0andTruea value of1.
The code, in essence, is adding 0 or 1 to n based on the value of parity and if n is currently even or odd.
A short demo may illustrate this better.
First, n & 1 producing 0 or 1:
>>>n = 10# even>>>bin(n) # the binary representation of 10
'0b1010'
>>>n & 1# should be 0, as the last bit is 0
0
>>>n = 11# odd>>>bin(n) # the binary representation of 11
'0b1011'
>>>n & 1# should be 1, as the last bit is 1
1
Next, the parity != 0 or parity != 1 part; note that I assume parity is limited to 0 or 1, it really doesn't make sense for it to have other values:
>>>parity = 0>>>parity != 1
True
>>>parity != 0
False
>>>parity = 1>>>parity != 1
False
>>>parity != 0
True
Last, that booleans are integers:
>>>isinstance(True, int)
True
>>>int(True)
1
>>>10 + True
11
>>>10 + False
10
The formula looks like it is calculating a CRC checksum.
Solution 2:
Lets break this down:
(n += (parity != (n & 1)))
(n & 1) this is bitmask, and takes the value of the smallest (least significant bit) of n.
parity != this is true if parity is different from the result of (n & 1)
n += this increments n by whatever value the rest of the line returns.
n parity output(increment of n)
011110101000From the above table you can see that it functions like an XOR of n's LSB and parity.
Notes: Usually parity is the oddness(1) or evenness(0) of a data packet.
Hope this helps! Enjoy.
Post a Comment for "Understanding Python Bitwise, Arithmetic, And Boolean Operators"