[Python-ideas] Negative hexes

MRAB python at mrabarnett.plus.com
Sun Dec 4 03:14:56 CET 2011

On 04/12/2011 02:06, Nick Coghlan wrote:
> On Sun, Dec 4, 2011 at 11:17 AM, Guido van Rossum<guido at python.org>  wrote:
>> On Sat, Dec 3, 2011 at 5:13 PM, Nick Coghlan<ncoghlan at gmail.com>  wrote:
>>> On Sun, Dec 4, 2011 at 3:07 AM, Antoine Pitrou<solipsis at pitrou.net>
>>> wrote:
>>>>> This is because Python's integers are not limited to 32 bits or 64
>>>>> bits. If
>>>>> you read PEP 237, you'll see that this was one of the hardest
>>>>> differences
>>>>> between ints and longs to be resolved. You'd have to include an
>>>>> infinite
>>>>> number of leading 'F' characters to format a negative long this way...
>>>> That's a fair point :)
>>> Random thought... could we use the integer precision field to fix
>>> *that*, by having it indicate the intended number of bytes in the
>>> integer?
>>> That is, currently:
>>>>>> "{:.4x}".format(31)
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in<module>
>>> ValueError: Precision not allowed in integer format specifier
>>> What if instead that produced:
>>>>>> "{:.4X}".format(31)
>>> 0000001F
>>>>>> "{:.4X}".format(-31)
>> Usually that field is measured in characters/digits, so this should probably
>> produce FFE1; you'd need {:.8X} to produce FFFFFFE1. This would then
>> logically extend to binary and octal, in each case measuring
>> characters/digits in the indicated base.
> True, I guess it's just a matter of dividing the bit width by 2 for
> binary, 3 for octal (rounding up) and 4 for binary. (My brain was
> locked into bytes mode for some reason, so converting to character
> counts seemed overly complicated - of course, if you go directly from
> bits to characters, it's no more complicated than converting to a
> bytes count).
> ".4d" would still raise an exception, though - I don't know of any
> obvious way to make two's complement notation meaningful in base 10.
It wouldn't be two's complement in that case, it would be ten's
complement. (Ever used BCD arithmetic in assembly language? :-))

Actually, would it really be two's complement in octal or hexadecimal
either? Wouldn't it be eight's complement and sixteen's complement

> For numbers that didn't fit in the specified precision, I'd also
> suggest raising ValueError.
> This would be tinkering with the behaviour of builtin, so I guess it
> would need a PEP? (I already have too many of those in train...
> although I did just tidy that up a bit by officially deferring
> consideration of the ImportEngine PEP until 3.4 at the earliest)

More information about the Python-ideas mailing list