Skip to content Skip to sidebar Skip to footer

Understanding Python Bitwise, Arithmetic, And Boolean Operators

I'm new to Python and not able to understand this. Can someone help break down the statement for me? Both n and parity are integers n += parity != n & 1

Solution 1:

The expression is evaluated as n += (parity != (n & 1)), and the results are:

  • n & 1 is a bitmask, it masks the integer n down to the least-significant bit. If n is odd, it will be 1, if it is even, that bit will be 0.

  • parity != 0 or parity != 1 produces a boolean result, True or False, signalling if parity was not equal to the 0 or 1 on the right.

  • The resulting True or False is added up to n, as if you did n = n + True or n = n + False. The Python boolean type is a subclass of int and False has an integer value of 0 and True a value of 1.

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"