简体   繁体   中英

Is there any built-in function to get the binary format of a negative integer in Python?

>>> 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.

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:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM