New submission from Raymond Hettinger:

The current 'b' formatting code in inconvenient for emulating, demonstrating, 
and teaching two's complement arithmetic.  The problem is that negative inputs 
are always formatted with a minus sign.  I propose that some formatting code be 
provided for fixed-width display where the leading bit is a sign bit.

For example, if code were a capital 'B' and the total width were 8-bits:

    >>> x = -12
    >>> format(12, '08B')
    '11110100'

Currently, to achieve the same effect, one of the following is used:

    >>> format(x if x >= 0 else x + 2**8, '08b')
    '11110100'

or 

    >>> format(x & (2**8 - 1), '08b')
    '11110100'

For values outside the valid range, perhaps a ValueError could be raised:

    >>> format(-200, '08B')
    Traceback (most recent call last):
    ...
    ValueError:  Expected value in range -128 <= x < 128, not -200

I'm not sure what the right code should be.  The idea of capital 'B' is 
attractive, but we already have a different relationship between 'X' and 'x'.   
There could also be a modifier symbol such as '!' in '!8b'.

----------
components: Interpreter Core
messages: 295162
nosy: mark.dickinson, rhettinger, talin
priority: low
severity: normal
status: open
title: Add integer formatting code for fixed-width signed arithmetic (2's 
complement)
type: enhancement
versions: Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue30571>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to