Is there no function to convert a hex number to decimal?

Larry Whitley ldw at us.ibm.com
Fri Jul 7 16:24:48 EDT 2000


Here's another way:

hex = "abcd"
dec = eval( "0x"+hex)

Don't know which is better, faster, etc...

Larry



"Markus Gritsch" <gritsch at iue.tuwien.ac.at> wrote in message
news:3960677C.BED04E21 at iue.tuwien.ac.at...
> Markus Gritsch wrote:
>
> > Hi!
> >
> > Although there are several built in functions to convert numbers from
> > decimal to hex or oct, it seems that there is no function which can do
> > the same in the reverse direction.  Of course I can write 0xff, but
> > what should I do, if I have a string containing a hex value?
> > Currently I use this brute code:
> >
> > hex_dec = {}
> > for i in range(256):
> >     hex_dec[hex(i)[2:]] = i
> >
> > def dec(hex_string):
> >     return hex_dec[string.lower(hex_string)]
> >
> > But I am not entirely happy with it, because I have to generate this
> > clumsy dict, and the function works only for two-digit-hex-numbers.
> >
> > Is there really no other way?
>
> I found the solution in the string module:
> atoi (s[, base]) and atol (s[, base])
>
> BTW, these functions will become obsolete in python 2.0, because there
will be an
> optional "base" argument to the built-in functions long() and int()
>
> --
>
|\/\/\/|
> /------------------------------------------------------------------\  |
|
> | Markus GRITSCH                 | phone:    +43 / 1 / 58801-36015 |  |
|
> | Institute for Microelectronics | cellular: +43 / 676 / 4973431   |  |
(o)(o)
> | Technical University of Vienna | fax:      +43 / 1 / 58801-36099 |  C
_)
> | Gusshausstrasse  27-29 / E360  | email: gritsch at iue.tuwien.ac.at |   |
,___|
> | A-1040  Vienna / AUSTRIA       | SMS:   436764973431 at max.mail.at |   |
/
> \------------------------------------------------------------------/
/____\
>                                                                      /
\
> "Computers let you make more mistakes faster than any other invention in
human
>  history, with the possible exception of handguns and tequila."
>                                                                Mitch
Radcliffe
>
>
>





More information about the Python-list mailing list