Bitwise not in python over unsigned numbers [duplicate]

I want to do a bitwise not in Python, but withouth taking care of the sign, as C would do. For example:

>>> x = 4
>>> y = ~x
>>> bin(x)
'0b100'
>>> bin(y)
'0b101'

In the above code, y is 0b101, but I want it to be 0b011, literally the bitwise not applied to number 4. How can I do this?


Solution 1:

Since Python ints are both signed and not a defined size of bits, the easiest way is to just XOR with an all 1's mask of the required bit length.

For example to get a NOT for 4 bits:

bin(x ^ 0b1111)

Test:

>>> x = 4
>>> bin(x)
'0b100'
>>> bin(x ^ 0b1111)
'0b1011'

Solution 2:

you could generate a mask of the bit length of x and xor that with x:

x = 4  # 0b100
width = x.bit_length()
mask = (1 << width) - 1  # mask = 0b111
y = x ^ mask
print(f"{y:0{width}b}")  # '011'