使用BigInts创建位掩码



是否有更有效的方法来执行以下计算?它工作得很好,但告诉我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。当你这样做时,Bigint的行为是正确的:

>>> bin(255 & ~(1 << 3))
'0b11110111'
>>> bin(65535 & ~(1 << 3))
'0b1111111111110111'
>>> bin(75557863725914323419135 & ~(1 << 3))
'0b1111111111111111111111111111111111111111111111111111111111111111111111110111'

这是因为负数前面有一个"无限"的1字符串。因此,当你补一个正数(它以一个由零组成的"中缀"字符串开始)时,你会得到一个负数(确切地说是-(x + 1))。只是不要相信负数的bin表示;它不能反映内存中的实际位。

所以你可以这样重写unset_mask

def unset_mask(index):
    return ~(1 << index)
x = 0b11111111
x &= unset_mask(3)
print x == 0b11110111  # prints True

您可以使用它来清除x:中的一个位

x &= ~(1 << index)

这将取消设置位:

x ^= 1 << 3 & x

在一个函数中:

def unset_bit(x, n):
    return 1 << n & x ^ x

最新更新