Search code examples
pythonbit-manipulationbitwise-not

What is the exact definition of bitwise not in Python, given arbitrary length integers?


Bitwise not (~) is well-defined in languages that define a specific bit length and format for ints. Since in Python 3, ints can be any length, they by definition have variable number of bits. Internally, I believe Python uses at least 28 bytes to store an int, but of course these aren't what bitwise not is defined on.

How does Python define bitwise not:

  1. Is the bit length a function of the int size, the native platform, or something else?
  2. Does Python sign extend, zero extend, or do something else?

Solution

  • Python integers emulate 2's-complement represenation with "an infinite" number of sign bits (all 0 bits for >= 0, all 1 bits for < 0).

    All bitwise integer operations maintain this useful illusion.

    For example, 0 is an infinite number of 0 bits, and ~0 is an infinite number of 1 bits - which is -1 in 2's-complement notation.

    >>> ~0
    -1
    

    It's generally true that ~i = -i-1, which, in English, can be read as "the 1's-complement of i is the 2's-complement of i minus 1".

    For right shifts of integers, Python fills with more copies of the sign bit.