hex and unsigned longs

Alex Martelli aleax at aleax.it
Sat Apr 12 17:07:57 CEST 2003

Igor V. Rafienko wrote:

> The documentation for the built-in function hex() says that hex()
> always returns an unsigned literal. However, on my 2.2.1 python, I get

Yes, I believe you've identified a bug in the docs.

> the following results:
>>>> hex( 1 )
> '0x1'
>>>> hex( 1L )
> '0x1L'
>>>> hex( -1 )
> '0xffffffff'
>>>> hex( -1L )
> '-0x1L'
> The literal in the last case is obviously not unsigned. What am I
> missing? (I.e. why are longs treated differently than ints by hex?)

hex is trying to ensure eval(hex(x))==x (when hex and eval are taking
place on the same machine, or more generally on machines of the same
word size).  hex just can't ensure that when type(x) is long, except
by using an explicit - sign; therefore, the statement in the docs that
"this always yields an unsigned literal" is overbroad -- it should be
slightly nuanced to "this always yields an unsigned literal for any
int argument", IMHO.  You can submit a documentation patch (or even just
a bug report) to sourceforge, just like you can submit bug reports or
patches for the interpreter and library parts of Python (it's a good
idea to doublecheck here, as you've done, to ensure you've actually
found an outright bug, like in this case -- bravo!).


More information about the Python-list mailing list