# hex string to hex value

mensanator at aol.com mensanator at aol.com
Wed Nov 23 00:56:25 CET 2005

```tim wrote:
> but then i get :
>
>  >>> m
> 66
>  >>> n=int(hex(m))
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> ValueError: invalid literal for int(): 0x42
>  >>>
>
> what am I missing here ?

Avnit's solution was wrong. When converting a string, you
must state what base you are converting from.

>>> int(hex(m),16)
66

Fredrik Lundh's solution works if the hex string starts with "0x"
(which it will when the string is created with the hex function).

>>> int(hex(m),0)
66

But it won't work without the "0x".

>>> int('0x1A',0)
26
>>> int('0x1A',16)
26
>>> int('1A',16)
26
>>> int('1A',0)

Traceback (most recent call last):
File "<pyshell#18>", line 1, in -toplevel-
int('1A',0)
ValueError: invalid literal for int(): 1A

> thank you
> Tim
>
> avnit wrote:
>
> >If you just want to convert a string to an integer, it would be:
> >
> >
> >
> >>>>int(n)
> >>>>
> >>>>
> >
> >in your case it would be:
> >
> >
> >
> >>>>m=66
> >>>>n=int(hex(m))
> >>>>
> >>>>
> >
> >
> >

```