hex string to hex value

Fredrik Lundh fredrik at pythonware.com
Tue Nov 22 18:28:15 EST 2005


"tim" <tim.vets at skynet.be> wrote:

> This is probably another newbie question...but...
> even after reading quite some messages like '..hex to decimal',
> 'creating a hex value' , I can't figure this out:
> If i do
> >>> m=66
> >>> n=hex(m)
> >>> n
> '0x42'
> i cannot use n as value for a variable that takes hex values, because it
> throws:
>
> error: required argument is not an integer
>
> >>> int(n)
> gives me:
> Traceback (most recent call last):
>  File "<interactive input>", line 1, in ?
> ValueError: invalid literal for int(): 0x42

int() is a function, not a variable, and it doesn't take a hex value if
you call it with a single argument.

if you want int() to interpret the string you pass it as a Python literal,
pass in 0 as the second argument:

    >>> int("0x42", 0)
    66
    >>> int("0x42", 0) == 0x42
    True

</F> 






More information about the Python-list mailing list