Converting a hex string to a number

Delaney, Timothy tdelaney at avaya.com
Tue Jul 9 20:44:12 EDT 2002


> From: Matt Gerrans [mailto:matt_gerrans at hp.com]
> 
> 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.

I'm really hoping there's a missing smiley here ...

How the hell is the above better in any way shape or form than:

# assumes s is a string of form 12345 i.e. any 0x has been trimmed from the
start

n = long(s, 16)

???

Tim Delaney





More information about the Python-list mailing list