Converting a hex string to a number

Matt Gerrans matt_gerrans at hp.com
Tue Jul 9 19:10:58 EDT 2002


> >>On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote:
> >>> eval!
> >>Overkill. Unsafe. Ugly. Lame.
> >What do you mean by unsafe?
> Something like the following could happen (don't try it!)
> # eval('system("rm -rf /")')

Hey, that has no effect on my Windows system!   Could this be because of
Bill Gates' recent one-month edict that Microsoft focus on making Windows
secure?  ;-)

(I don't think I'll test it on my Linux box, though!)

Anyway, that's assuming you have no control over the input; if that is the
case, you could filter it easily enough:

if re.match(r'0x(\d|[a-f])*', string, re.I ):
   n = eval(string)
else:
   n = 0 # Could alternatively raise a ValueError, or something like that,
here.

You could change this to allow for decimal input, etc., while still not
inviting a nefarious chunk of code.

(Someone will probably suggest a better re for this...)





More information about the Python-list mailing list