Eryk Sun added the comment:
bin() returns a Python literal, which thankfully requires an explicit sign. 2's
complement literals would be prone to human error. If you want 2's complement,
you can write your own function. For example:
def mybin(number, nbits=None, *, signed=True):
if not signed and number < 0:
raise ValueError('number must be non-negative')
if nbits is None:
return bin(number)
bit_length = number.bit_length()
if signed and number != -2 ** (bit_length - 1):
bit_length += 1
if nbits < bit_length:
raise ValueError('%d requres %d bits' % (number, bit_length))
number &= 2 ** nbits - 1
return format(number, '#0%db' % (nbits + 2))
>>> mybin(12)
'0b1100'
>>> mybin(-12)
'-0b1100'
>>> mybin(12, 8)
'0b00001100'
>>> mybin(-12, 8)
'0b11110100'
>>> mybin(12, 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in mybin
ValueError: 12 requres 5 bits
Obviously when parsing a number you need to know whether it's two's complement
or unsigned.
>>> mybin(12, 4, signed=False)
'0b1100'
>>> mybin(-4, 4)
'0b1100'
----------
nosy: +eryksun
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue25999>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com