Search code examples
pythonbit-manipulationxor

Bitwise not, can somebody explain this example?


Can somebody explain this example through binary digits?

>>> ~11
-12

Solution

  • Using 8 bit representation (you can use larger representations for the same results):

    ~11 => ~ b 00001011
    

    Applying NOT operator yields (1 turns to 0 and vice versa):

    ~(b 00001011) => b 11110100
    

    The result is negative (since the left most bit is the sign bit). To discover its value, apply 2's complement operator (see here):

    b 11110100, negate bits:
    b 00001011, add 1:
    +        1
    ----------
    b 00001100 => 12
    

    Meaning that the result was -12.