Why the binary representation is different from python compiler than what we know on paper?

后端 未结 1 485
傲寒
傲寒 2021-01-21 03:45

Bitwise NOT is the first complement, for example:

  • x = 1 (binary: 0001)
  • ~x = -2 (binary: 1110)

Hence, my questio

相关标签:
1条回答
  • 2021-01-21 04:18

    Two's complement inherently depends on the size of a number. For example, -2 on signed 4-bit is 1110 but on signed 8-bit is 1111 1110.

    Python's integer type is arbitrary precision. That means there is no well-defined leading bit to indicate negative sign or well-defined length of the two's complement. A two's complement would be 1... 1110, where ... is an infinite repetition of 1.

    As such, Python's integer are displayed as a separate sign (nothing or -) and the absolute number. Thus, -2 becomes - and 0b10 – i.e. - 2. Similarly, -5 becomes - and 0b101 – i.e. - 5.

    Note that this representation is merely the standard representation to be human-readable. It is not necessarily the internal representation, which is implementation defined.

    0 讨论(0)
提交回复
热议问题