Understanding Python bitwise, arithmetic, and boolean operators

前端 未结 2 532
[愿得一人]
[愿得一人] 2021-01-26 22:18

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 &a         


        
2条回答
  •  迷失自我
    2021-01-26 22:46

    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)
    0      1         1
    1      1         0
    1      0         1
    0      0         0
    

    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.

提交回复
热议问题