Is there a built in function in python which will convert a binary string, for example '111111111111', to the two's complement integer -1?
But '111111111111' as an integer is 4095. What did you actually mean?
You could always
int('111111111111',2)
A couple of implementations (just an illustration, not intended for use):
def to_int(bin):
x = int(bin, 2)
if bin[0] == '1': # "sign bit", big-endian
x -= 2**len(bin)
return x
def to_int(bin): # from definition
n = 0
for i, b in enumerate(reversed(bin)):
if b == '1':
if i != (len(bin)-1):
n += 2**i
else: # MSB
n -= 2**i
return n
>>> bits_in_word=12
>>> int('111111111111',2)-(1<<bits_in_word)
-1
This works because:
The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2^N for an N-bit two's complement). The two's complement of the number then behaves like the negative of the original number in most arithmetic, and it can coexist with positive numbers in a natural way.
It's not built in, but if you want unusual length numbers then you could use the bitstring module.
>>> from bitstring import BitString
>>> a = BitString(bin='111111111111')
>>> a.int
-1
The same object can equivalently be created in several ways, including
>>> b = BitString(int=-1, length=12)
It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:
>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 0b111111111111 0xfff 0o7777