converting hex number contained in a string to an integer
Author Message
converting hex number contained in a string to an integer

Hello all,

I have a string containing a number. This is an
hex number. How can I convert this to an integer?

For instance:

Quote:
>>> hexnumber
'32'
>>> 0x32
50
>>> int(0x32)

50  # this is the result I want to get
Quote:
>>> hexnumber = '0x' + hexnumber
>>> hexnumber
'0x32'
>>> int(hexnumber)

Traceback (innermost last):
File "<interactive input>", line 1, in ?
ValueError: invalid literal for int(): 0x32

How can I do this? I am sure it is really easy,
but I am just beginnig with
Python.

Best Regards.
--
Eduardo Fernandez

Sent via Deja.com http://www.*-*-*.com/

Sat, 07 Dec 2002 03:00:00 GMT
converting hex number contained in a string to an integer

Quote:

>Hello all,

>I have a string containing a number. This is an
>hex number. How can I convert this to an integer?
...
>How can I do this? I am sure it is really easy,
>but I am just beginnig with
>Python.
>>> eval('0x32')
50
>>> import string

# Forces base to 16(hex)
Quote:
>>> string.atoi('32',16)

50
# Guesses base from leading characters
Quote:
>>> string.atoi('0x32',0)

50

--

Megabaud Internet-palvelut

Sat, 07 Dec 2002 03:00:00 GMT
converting hex number contained in a string to an integer

Quote:

> I have a string containing a number. This is an
> hex number. How can I convert this to an integer?

> >>> hexnumber
> '32'
> >>> 0x32
> 50
> >>> int(0x32)
> 50  # this is the result I want to get
> >>> hexnumber = '0x' + hexnumber
> >>> hexnumber
> '0x32'
> >>> int(hexnumber)
> Traceback (innermost last):
>   File "<interactive input>", line 1, in ?
> ValueError: invalid literal for int(): 0x32
>>> import string
>>> string.atoi(hexnumber, 16)

50

Roland Schlenker

Sat, 07 Dec 2002 03:00:00 GMT
converting hex number contained in a string to an integer

Quote:

> >I have a string containing a number. This is an
> >hex number. How can I convert this to an integer?
> >How can I do this? I am sure it is really easy,
> >but I am just beginnig with
> >Python.
> # Forces base to 16(hex)
> >>> string.atoi('32',16)
> 50
> # Guesses base from leading characters
> >>> string.atoi('0x32',0)
> 50

Note that in python 1.6, you can do the above two things like this:

Quote:
>>> int('0x32',16)
50
>>> int('0x32',0)

50

--

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!

Sat, 07 Dec 2002 03:00:00 GMT

 Page 1 of 1 [ 4 post ]

Relevant Pages