[Python-ideas] Negative hexes

Guido van Rossum guido at python.org
Sat Dec 3 18:05:02 CET 2011


On Sat, Dec 3, 2011 at 8:45 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:

> On Sat, 3 Dec 2011 14:31:51 +1000
> Nick Coghlan <ncoghlan at gmail.com> wrote:
> >
> > If you really want that (Why would you?) and so long as the numbers
> > aren't negative:
> >
> >     "0B{:b}".format(number)
> >     "0O{:o}".format(number)
> >
> > The only reason 'X' is provided for hexadecimal formatting is to
> > capitalize the letters that appear within the number itself.
>
> By the way, any reason why hex output represents negative number with a
> negative sign (instead of the more usual 2s-complement representation)?
>
> It's not too difficult to normalize by hand (e.g. add 2**32 if you know
> the number is a 32-bit one) but it always irks me that Python doesn't
> do it by default. I cannot think of a situation where the "sign" is
> relevant when printing a hex number: hex is about the raw binary
> representation of the number.
>

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

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111203/bf412482/attachment.html>


More information about the Python-ideas mailing list