有没有更有效率的方法来执行以下计算?它能正常工作,但是我感觉 x &= (1 << 8) - 1 ^ 1 << 3
可以被简化以避免一些计算并提高速度。
def unset_mask(width, index):
return (1 << width) - 1 ^ 1 << index
x = 0b11111111
x &= unset_mask(8, 3)
assert x == 0b11110111
width
。当您这样做时,Bigints会表现出正确的方式:>>> bin(255 & ~(1 << 3))
'0b11110111'
>>> bin(65535 & ~(1 << 3))
'0b1111111111110111'
>>> bin(75557863725914323419135 & ~(1 << 3))
'0b1111111111111111111111111111111111111111111111111111111111111111111111110111'
-(x + 1)
)。只是不要相信负数的bin
表示法;它不能反映内存中实际的位。所以你需要像这样重写unset_mask
:def unset_mask(index):
return ~(1 << index)
x = 0b11111111
x &= unset_mask(3)
print x == 0b11110111 # prints True
这将取消该位:
x ^= 1 << 3 & x
def unset_bit(x, n):
return 1 << n & x ^ x
您可以使用此功能来清除 x
中的一些内容:
x &= ~(1 << index)