0
>>> bin(-1)
'-0b1'

bin() function returns '-' and '0b' and the absolute value of the input negative number. (I knew that python will suffer underflow, but it will never overflow.) Is that how python store a negative number? Store negative sign and its absolute value? Where is the sign bit in Python?

If I input:

int('1000..(many many zeros)..0000',2)

No matter how many zeros, the '1' on the head will never be regard as minus sign bit? Therefore, does that mean the relationship between binary and integer isn't the same as that in C++? I am confused with the original binary rules in python.

  • Have you tried to find something along the line of two's complement in Python? https://wiki.python.org/moin/BitwiseOperators has a fair bit of good information and explanation – woozyking Sep 24 '18 at 05:25
  • Check this question : https://stackoverflow.com/questions/16255496/format-negative-integers-in-twos-complement-representation – Arkistarvh Kltzuonstev Sep 24 '18 at 05:27
  • Possible duplicate of [Format negative integers in two's complement representation](https://stackoverflow.com/questions/16255496/format-negative-integers-in-twos-complement-representation) – blhsing Sep 24 '18 at 05:39

1 Answers1

-1

Numbers in python have arbitrary range. But, given a word size, you can get the usual two-complemente word:

def two_comp(x, n):
    return bin(2**n+x)[-n:]
Vitor SRG
  • 664
  • 8
  • 9