Q:

Creating a bit mask with BigInts

Is there a more efficient way of performing the following calculation? It works fine, but something tells me that x &= (1 << 8) - 1 ^ 1 << 3 can be written to avoid some calculations and increase speed.
def unset_mask(width, index):
    return (1 << width) - 1 ^ 1 << index

x = 0b11111111
x &= unset_mask(8, 3)
assert x == 0b11110111

A:

Actually, you don't need to state the width. Bigints behave the right way when you do this:
>>> bin(255 & ~(1 << 3))
'0b11110111'
>>> bin(65535 & ~(1 << 3))
'0b1111111111110111'
>>> bin(75557863725914323419135 & ~(1 << 3))
'0b1111111111111111111111111111111111111111111111111111111111111111111111110111'

It's because negative numbers have an "infinite" string of ones preceding them. So when you complement a positive number (which starts with an "infinte" string of zeros), you get a negative number (-(x + 1) to be exact). Just don't trust the bin representation of negative numbers; it doesn't reflect the actual bits in memory. 
So you would rewrite unset_mask like so:
def unset_mask(index):
    return ~(1 << index)

x = 0b11111111
x &= unset_mask(3)
print x == 0b11110111  # prints True

