Search code examples
pythonbit-manipulationunsignedbitwise-not

Bitwise not in python over unsigned numbers


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

  • 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'