Understanding Python Bitwise, Arithmetic, And Boolean Operators
Solution 1:
The expression is evaluated as n += (parity != (n & 1))
, and the results are:
n & 1
is a bitmask, it masks the integern
down to the least-significant bit. Ifn
is odd, it will be1
, if it is even, that bit will be0
.parity != 0
orparity != 1
produces a boolean result,True
orFalse
, signalling ifparity
was not equal to the0
or1
on the right.The resulting
True
orFalse
is added up ton
, as if you didn = n + True
orn = n + False
. The Python boolean type is a subclass ofint
andFalse
has an integer value of0
andTrue
a 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)
011110101000
From 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"