[Tutor] built-in hex->int question

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 7 Jan 2002 23:24:34 -0800 (PST)


On Tue, 8 Jan 2002, Huuuuuu wrote:

> Why understands the float() function a string argument but not
> integer-cast-functions?
> 
> >>> int('0xaf')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 0xaf


How strange!

###
>>> int('0xaf')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 0xaf
>>> int('0xaf', 16)
175
###


Hmmm...  So as long as Python knows which base it's working on, the
conversion works.  Time to look at the documentation:


""" int(x[, radix]) Convert a string or number to a plain integer. If the
argument is a string, it must contain a possibly signed decimal number
representable as a Python integer, possibly embedded in whitespace; this
behaves identical to string.atoi(x[, radix]). The radix parameter gives
the base for the conversion and may be any integer in the range [2, 36],
or zero. If radix is zero, the proper radix is guessed based on the
contents of string; the interpretation is the same as for integer
literals. If radix is specified and x is not a string, TypeError is
raised. Otherwise, the argument may be a plain or long integer or a
floating point number. Conversion of floating point numbers to integers
truncates (towards zero)."""


Ah!  The documentation mentions that if the radix is zero, then Python
will try to guess the way we expect it to:

###
>>> int('0xaf', 0)
175
###

And that's probably what you're looking for.  Apparently, the float()
function will do this radix guessing thing for us, which is why:

###
> >>> float('0xaf')
> 175.0
###

worked for you before.



Hope this helps!