Converting hex string to an integer

Michael Ströder michael at stroeder.com
Thu Aug 26 15:16:29 CEST 2004


Peter Hansen wrote:
> Rick Holbert wrote:
> 
>> Derek Fountain wrote:
>>
>>> Given the character string "0x00A1B2C3" arriving at sys.argv[1] how do I
>>> convert that to an integer which I can do some math on?
>>
>> i = eval(sys.argv[1])
> 
> That's dangerous advice to a newbie if not qualified carefully.
> 
> Derek, "eval" could be the source of serious security problems
> if you don't understand its power.

Yes, eval() is risky! Try to get rid of eval() or you MUST protect each and 
every call to eval() with paranoid parameter checking!

int(sys.argv[1],16) would be a better approach here...

 >>> int("0x00A1B2C3",16)
10597059
 >>> int("__import_('os').system('rm -rf /')",16)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): __import_('os').system('rm -rf /')
 >>>

Ciao, Michael.



More information about the Python-list mailing list