我是 Python 新手,无法理解这一点。有人可以帮我分解声明吗?
n和parity都是整数
n += parity != n & 1
请您参考如下方法:
表达式被计算为n += (parity != (n & 1)),结果为:
n & 1是一个位掩码,它将整数n掩码到最低有效位。如果n为奇数,则为1,如果为偶数,则该位为0。parity != 0或parity != 1产生一个boolean 结果,True或False,如果parity不等于右侧的0或1,则发出信号。生成的
True或False加到n中,就好像您做的那样n = n + True或n = n + False。 Python bool 类型是int的子类,False的整数值为0和True1的值。
代码,本质上就是根据parity的值,在n上加上0或1如果 n 当前是偶数或奇数。
一个简短的演示可能会更好地说明这一点。
首先,n & 1 产生 0 或 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
接下来,parity != 0 或 parity != 1 部分;请注意,我假设 parity 仅限于 0 或 1,它具有其他值确实没有意义:
>>> parity = 0
>>> parity != 1
True
>>> parity != 0
False
>>> parity = 1
>>> parity != 1
False
>>> parity != 0
True
最后, bool 值是整数:
>>> isinstance(True, int)
True
>>> int(True)
1
>>> 10 + True
11
>>> 10 + False
10
这个公式看起来像是在计算一个 CRC checksum .
